Problem with DOMContentLoaded in Firefox

I created a script that works with Dom, so it must wait for Dom to be ready before performing each operation. I want this script to be enabled in two ways:

  • In the head tag so that it is loaded before Dom is ready. I used document.addEventListener("DOMContentLoaded",function(){...},false) for this, and it works well
  • Loads dynamically when Dom is already loaded. In this case, the script does not work, because for some reason, if Dom is already loaded, the DOMContentLoaded event does not fire

So, I want to know if there is a way to check if Dom is really loaded so that the script can execute the code without using the DOMContentLoaded event?

PS: it must be an external script, so I can not control the page on which it will be included

+4
source share
5 answers

Ok, this is cheesy, but it should work: Wrap your external script with init ():

eg. (and I'm just guessing here)

 var myModule = { init: function { //all the code goes here /.. } } 

Then put the script back in the header tag and add the script tag at the very bottom of the DOM markup

 <script> myModule.init(); </script> 

Again, I would not recommend it normally, but if you need to avoid checking the loaded DOM event, what would I do

+2
source

One of the easiest ways to do this is to check if you can get an ElementById for something at the end of the page. Sort of:

 if (document.getElementById('footer')) { /* Dom is probably loaded */ } else { /* Dom is probably NOT loaded */ } 

But actually the best thing is probably to make sure that the code is always called in the same way. instead, you can use the onload event, as this will work in all browsers and, as a rule, only a second after the DOMContentLoaded event. But I guess it really is up to you.

0
source

Define your function: function domReadyHandler() { /* ... */ }

Add event listener: document.addEventListener('DOMContentLoaded', domReadyHandler, false);

Run a handler after dynamically loading your content: function myXhrCallback() { /* ... */; domReadyHandler(); } function myXhrCallback() { /* ... */; domReadyHandler(); }

0
source

You can set the global var by indicating that the script is dynamically turned on, depending on which you can run the load listener when the script is evaluated.

 window.SCRIPT_IS_DYNAMICALLY_LOADED = true; < include script> 

In the script:

 if (window.SCRIPT_IS_DYNAMICALLY_LOADED) { domContentLoadedListener(); } else { document.addEventListener("DOMContentLoaded",domContentLoadedListener, false); } 
0
source

Check value for document.readyState. If the value is "complete", you can execute the script, if this is something else, add a listener.

0
source

Source: https://habr.com/ru/post/1304890/


All Articles