Question

To test if a page is loaded, it is possible to add a "load" event listener on the window: window.addEventListener ("load", function(){});

But in certain case, this event is never fired even if everything is loaded: imagine that you want to execute some JS when the page is loaded, but this page is not get as usual. It is loaded into an iframe without setting its "src" property but by doing iframe.contentWindow.document.write ("<!DOCTYPE html><html>...</html>"); In this case, the "load" event is not thrown.

But whatever, inside this page, it is still necessary to be able to known when the page is like "loaded", to begin some js stuff.

Can i assume that if the end of the html is reached, then the page is loaded? If the answer si "yes", then starting the JS in a <script>tag at the end of the page would do the trick...

In other words: in a normal load workflow (by setting the "src" attribute) does some other "init" processes still asynchronously run at the end of the page (like a css engine init process), and the "load" event is fired only when all of these processes terminate? are these processes also present when loading a page by using document.write?

Thank you for your attention.

Was it helpful?

Solution

An answer to the question in the header is no.

Practically DOMContentLoaded fires when </body> is met, but for example some images can still be under loading. window.onload fires after all the content and resources (like images and contents of iframes) of the page have been loaded.

When you write to any document using document.write() after that page has been parsed, write() implicitely opens the document, but it doesn't close it. "Ready" events can't be fired while the document is open. Hence after document.write()(s) you've to close the document manually:

document.close();

OTHER TIPS

With jQuery it's as easy as this:

$( document ).ready(function() {
  // Handler for .ready() called.
});

http://api.jquery.com/ready/

That event triggers once the DOM is ready which is most probably sufficient for starting DOM-Manipulations via JS. The onload event on the other hand triggers after all the assets to the page like images are loaded as well and can therefore take a little longer to be triggered.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top