Javascript like $(document).ready() for "modern HTML5" browsers

22,202
document.addEventListener('DOMContentLoaded', function () {
    /* ... */
});

The event "DOMContentLoaded" will be fired when the document has been parsed completely, that is without stylesheets* and additional images. If you need to wait for images and stylesheets, use "load" instead.

* only if the <script> is before the <link rel="stylesheet" ...>

Share:
22,202
Randy Hall
Author by

Randy Hall

I do some pretty odd web stuff. Basically, I'm an uneducated code monkey who likes to play. Sometimes, it turns out cool. Sometimes I build a square wheel. It's all good.

Updated on August 13, 2020

Comments

  • Randy Hall
    Randy Hall over 3 years

    This is most likely already a question somewhere, but I cannot find it, as EVERY single search turns up jQuery questions.

    I'm looking for a proven method to bind to the document being ready, much like jQuery's $(document).ready(). However, this is for a "modern browser only" page, with very light javascript, and I'd like to avoid loading jQuery here.

    Would someone kindly point me in the right direction?

    Thanks!

  • Randy Hall
    Randy Hall about 11 years
    I'll accept when I can - plugged it in, works like a charm! Thank you much.
  • Zeta
    Zeta about 11 years
    @RandyHall: You're welcome. You might want to have a look at github.com/addyosmani/jquery.parts/blob/master/… (it's not a jQuery plugin, but a independent part of jQuery).
  • Rich Apodaca
    Rich Apodaca about 10 years
    window.addEventListener('load') looks like the way to go: stackoverflow.com/questions/16404380/…
  • Zeta
    Zeta about 10 years
    @RichApodaca: Every “modern HTML5” browsers understands DOMContentLoaded. If you deal with ancient browsers, you need load.
  • Randy Hall
    Randy Hall almost 4 years
    Almost everything about that statement was wrong and doesn't answer the question
  • FantomX1
    FantomX1 over 3 years
    User doesn't necessarily wait, even though in some cases should. But let's regard it in the context. The functionality is not used terms that by document.write that it provides incomplete data the user to use step by step. Either way, there still has to be a check on the background, client-side js can't handle it. But for the generic scenario, for this question/usage what might be needed is waiting for the entire document/window to load, since seems like you don't have other option how to ensure eg Jquery is available when it's listed in the page footer and you somehow can't move it, afaik.