javascript event: get when document is textually fully loaded but scripts haven't ran yet

406 views Asked by At

DOMContentLoaded fires after document is loaded and its scripts ran, and I'd like to run my code before scripts were executed but after document.body.outerHTML ( document.childNodes[document.childNodes.length-1].outerHTML ) is full

I try this, but looks like it runs many times after is found also so now I do a timer 200ms job before executing mycode, but i'd like to do it without timers

var observer = new MutationObserver(function(mutations) 
{
    if(document.body && document.childNodes[document.childNodes.length-1].outerHTML.lastIndexOf("</html>")!=-1)
    {
        observer.disconnect();
        mycode();
    }
});
observer.observe(document, {subtree: true, childList: true}); 

Needs to work in Chrome (so beforescriptexecuted event won't work here)

2

There are 2 answers

6
Guffa On BEST ANSWER

You can't do that. Scripts are executed immediately, so they run before the document is fully loaded.

2
Rastko On

If you want to run something after all the "texts" as you call it are loaded but before other js, you need to run all your js at the very bottom of the page (that is, btw, proposed best practice) and run anything you need ot be ran first at the very top...

Note that js is highly concurrent - meaning that lots of stuff is happening simultaneously, so I recommend you wrap your first code to run in one anonymous function, and everything else in the other, so it gets executed first.

Your document.ready can also be in anon f.