3

Using jQuery, I can use the following function to execute code as soon as the DOM has loaded:

$(function() {
    // do stuff here
});

Or equivalently:

$(document).ready(function() { 
    // do stuff here
});

In trying to get a better understanding of raw javascript, I'm using this code to achieve a similar effect:

window.onload = function() {
    // do stuff here
}

Is this method cross-browser compatible? Are there any better ways to achieve this functionality?

aligray
  • 2,766
  • 4
  • 22
  • 33
  • jQuery solves the "cross-browser" issue and _is_ the "better way to achieve this functionality". – Sparky Jun 15 '11 at 03:50
  • Duplicate of http://stackoverflow.com/questions/3474037/window-onload-vs-body-onload-vs-document-onready – mrk Jun 15 '11 at 03:51

4 Answers4

9

Yes it is cross-browser compatible, but onLoad waits for everything on the page to load before it fires. Internally jQuery.ready uses the DOMContentLoaded event and a few hacks to support older browsers that don't support DOMContentLoaded. Most modern browsers support DOMContentLoaded including IE starting with version 9. You can test whether a browser supports DOMContentLoaded using this page.

If you are not using a DOM library such as jQuery which has built in support for DOMContentLoaded, you could use DOMContentLoaded and then fallback to onLoad if the browser doesn't support it.

(function () { // Encapsulating our variables with a IIFE
  var hasRun = false;  // a flag to make sure we only fire the event once
                       // in browsers that support both events
  var loadHandler = function (evt) {
    if (!hasRun) {
      hasRun = true;
      console.log('loaded via ' + evt.type);
    }
  };
  
  document.addEventListener('DOMContentLoaded', loadHandler, false);
  window.addEventListener('load', loadHandler, false);
}());

Unless you are expecting visitors with very old browsers like IE8, you are totally safe to just use DOMContentLoaded without a backup.

document.addEventListener('DOMContentLoaded', function (evt) {
  console.log('loaded via ' + evt.type);
}, false);
Useless Code
  • 10,586
  • 4
  • 30
  • 37
7

This is similar to what JQuery does:

window.$ = {};
$.ready = function(fn) {
  if (document.readyState == "complete")
      return fn();

  if (window.addEventListener)
      window.addEventListener("load", fn, false);
  else if (window.attachEvent)
      window.attachEvent("onload", fn);
  else
      window.onload = fn;
}

And to use it:

$.ready(function() {
  // code here...
});
Will
  • 17,297
  • 7
  • 45
  • 48
4

The window onload method is cross-browser compatible, but there is a better alternative.

  • The jQuery ready event fires when the DOM is ready.
  • The window onload event fires when all data is downloaded.

So, let's say you have lots of images (or one BIG one) on your page. The html file will finish downloading and be ready for manipulation long before the images are done downloading. So jQuery's ready event shoots and you can start doing great JavaScript stuff while all those pretty pics download.

That's one of the reasons it's a good idea to use a js library.

When there aren't that many images then the difference is negligible. Though, you can only set ONE method at a time on the onload event. You can, however, set jQuery's ready event multiple times and each method will get called sequentially.

Abishai Gray
  • 525
  • 2
  • 7
2

Cross-browser compatibility would have to depend on how you define the term "browser". Like for instance if it's a text based browser, then it might not be what you're looking for.

To answer your question, it will be cross-browser compatible if that particular browser warrants window.onload feature.

As a general guide, we usually use libraries that are tested so that we allow the libraries to take care of such "cross-browser" compatibility and we deal with the actual application logic.

Hope it helps!

Vern
  • 2,295
  • 1
  • 14
  • 18
  • Cheers for your answer! I'm trying to learn raw `JS` properly because I started learning with `jQuery`! – aligray Jun 15 '11 at 03:52
  • 1
    @aligray: I commend your efforts. I wish everyone had that desire. However, there is so much you cannot easily do with raw JavaScript, that you can do simply with jQuery. In other words, I don't think it's _"one or the other"_. I believe you can learn proper JavaScript **while** implementing your jQuery. Anything you no longer need because jQuery does it better, well, you no longer need it. Then again, I learned JavaScript more than 10 years ago. – Sparky Jun 15 '11 at 03:59
  • 2
    @aligray If you want to learn JS the "proper" way I would recommend reading Douglas Crockford's book _JavaScript: The Good Parts_ and Stoyan Stefanov's book _Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries_ both are excellent. If you are interested in this kind of library level stuff, John Resig's _Secrets of the JavaScript Ninja_ would be an great resource... if they ever finally publish it (it was originally slated for Fall 2008 when I pre-ordered it). – Useless Code Jun 15 '11 at 04:08
  • @Useless Code Thanks, I'll definitely look into them. – aligray Jun 15 '11 at 04:10