Loading script.js (external) using Domcontentloaded?

Asked

Viewed 508 times

0

I’ll introduce my test code summarized for 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);

shortener.js (external, 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 the <body> the DOM is already completed, and due to this reason the external script cannot execute its functionality.

  • You may be wondering why gave this wanting to do this, rather than simply add the script straight to the page?

It is that I intend to leave random this insertion , will be say (5 links) of several different companies of shortener, will be controlled by cookies when using one or other.

Sorry if I couldn’t explain my doubt clearly, I can try to be more detailed while doubting you if I didn’t understand something. I thank you from my heart who can help me, thank you very much :)

  • Since you are using PHP, it would not be easier to do this with it?

  • Opa @Guilhermecostamilam , my test page is in . php running on an apache localhost server , but the place that will run is only page . html, I would also like to know if there is any correction to solve the problem using only javascript. Thank you very much for the comment :)

2 answers

1


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

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

You can create the event yourself DOMContentLoaded artificially firing it at an element (in this case the Document).

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

var domContentLoadedEvent = new Event('DOMContentLoaded');
document.dispatchEvent(domContentLoadedEvent)

This fires the DOMContentLoaded on Document, causing the script now loaded the catch and be executed.

Detecting that the script has been loaded

Since you are loading the file dynamically, we can place an event to listen to when the file just clicked to trigger the event DOMContentLoaded

function triggerDOMContentLoaded() {
    var domContentLoadedEvent = new Event('DOMContentLoaded');
    document.dispatchEvent(domContentLoadedEvent);
}

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

    // podes usar a propriedade onload
    script.onload = triggerDOMContentLoaded;

    // ou um addEventListener, no entanto, o exemplo acima encaixa melhor no estilo que já estás a seguir
    script.addEventListener('load', triggerDOMContentLoaded);

    document.body.appendChild(script);
}
  • Perfect! @Leite, it didn’t even occur to me to create a new instance and apply it to Document. Let’s just take the last question with you, I did the confirmation by window.addeventlistener('load', update); event load , is there any more elegant way to confirm that it has already been loaded? because from what I checked I think I made confirmation that the entire page was loaded and not the script I entered rsrsrs, thank you very much for the help :)

  • I updated it with a small change to detect when the script was loaded

  • Thank you, regarding compatibility with IE 9 and other browsers the new Event() works as expected or not ?

  • No, in IE9 (and maybe 10?) you have to use the document.createEvent, you can use something like this (add the return event at the end of the function) https://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work/42089476#42089476

  • Nice , I already made the adaptation here tbm , I noticed that has incompatibility with the 'addeventlistener' also needing to make the use 'attachEvent' , proceed ? sorry again to disturb..

0

use if(statusTxt == "Success")

function open_exec32(){ 
$("#exec32").load("../../sitecorp/modal/01/modalEffects.js", 
function(responseTxt, statusTxt, xhr){  if(statusTxt == "success") {alert();} else {} ;
}); 
};

return works adapt to your project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.