Short of setting a variable inside of window.onload, is there a way to detect if the page has finished loading?
I'm injecting a bit of third party JS in a page that may or may not be fully loaded. I can't modify the page. I can't use JQuery.
I can add a function and poll it repeatedly until it returns true (page fully loaded). Any ideas?
32 Answers
I would make use of readyState.
For example first check if the document is loaded, and if not set up a listener:
if(document.readyState === 'ready' || document.readyState === 'complete') { doSomething(); } else { document.onreadystatechange = function () { if (document.readyState == "complete") { doSomething(); } } } You can check the document.readyState property.
From MDN:
Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded.