Browser-compatible way to bind events to page load

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

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

Or equivalently:

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

Trying to get a better idea of ​​raw javascript, I use this code to achieve a similar effect:

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

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

+3
source share
4 answers

, -, onLoad , , . jQuery.ready DOMContentLoaded , DOMContentLoaded. DOMContentLoaded, IE, 9. , DOMContentLoaded .

DOM, ​​ jQuery, DOMContentLoaded, DOMContentLoaded, onLoad, .

+7

, JQuery:

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;
}

:

$.ready(function() {
  // code here...
});
+7

onload -, .

  • jQuery , DOM .
  • onload .

, , ( ). html , . , jQuery , JavaScript, .

, js.

, . onload. , , jQuery ready , .

+4
source

Compatibility between browsers should depend on how you define the term “browser”. For example, if it is a text browser, perhaps this is not what you are looking for.

To answer your question, it will be cross-browser compatible if that particular browser guarantees the window.onload function.

As a general guide, we usually use tested libraries to allow libraries to take care of such cross-browser compatibility, and we are dealing with real application logic.

Hope this helps!

+2
source

All Articles