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?
Yes it is cross-browser compatible, but
onLoadwaits for everything on the page to load before it fires. InternallyjQuery.readyuses theDOMContentLoadedevent and a few hacks to support older browsers that don’t supportDOMContentLoaded. Most modern browsers supportDOMContentLoadedincluding IE starting with version 9. You can test whether a browser supportsDOMContentLoadedusing this page.If you are not using a DOM library such as jQuery which has built in support for
DOMContentLoaded, you could useDOMContentLoadedand then fallback toonLoadif the browser doesn’t support it.Unless you are expecting visitors with very old browsers like IE8, you are totally safe to just use
DOMContentLoadedwithout a backup.