Loading script.js (external) using DOMContentLoaded?

0

I'll introduce my test code for a better understanding.

index.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Teste</title>    
</head>
<body>
    <script src="script.js"></script>
</body>
</html>

script.js

function init() {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '//externo.com/js/encurtador.js';
    document.body.appendChild(script);
}

window.addEventListener("DOMContentLoaded", init);

shorter.js (external, I do not have access to the file)

document.addEventListener("DOMContentLoaded", function(e) {
    // Codigo que faz a analise de todas tags <a> e insere o url encurtado
});

My Problem

I'm trying to load an external script in which it also makes use of 'DOMContentLoaded'.

By my understanding (forgive me if I'm wrong) is that when the external script is inserted at the end of <body> the DOM is already completed, and because of this reason the external script can not execute its functionality. >

  • Are you wondering why this is what you wanted to do instead of simply adding the script straight to the page?

I want to make this insert random, let's say (5 links) from several different companies of the shortcuts, it will be controlled by cookies when using one or the other.

Sorry if I could not explain my question clearly, I can try to be more detailed as long as I doubt you have not understood something. Thank you from the heart who can help me, thank you:)

    
asked by anonymous 03.09.2018 / 21:51

1 answer

1

You are right, the problem is that when the encurtador.js file is included, the DOMContentLoaded event has already been triggered, so the new script will never be triggered.

Fortunately this is all javascript, and there is always way around.

You can create the event DOMContentLoaded artificially and fire it in an element (in this case the document ).

You will probably have to confirm that the <script> dynamically inserted has already been loaded (after being inserted into the page), and there are some ways to do this, but to trigger DOMContentLoaded , you can use

03.09.2018 / 23:33