jQuery provides a ready()
event to be attached to the document
object. This event makes use of the DOMContentLoaded
event to check whether your page has finished loading and the DOM is ready to be used. There are three ways to use this event in jQuery. In this post I'm going to discuss them with you.
The first way is to use the ready()
event on document
explicitly:
function doSomething() { return this; } $(document).ready(function() { doSomething(); });
The second way omits the document
object:
function doSomething() { return this; } $().ready(function() { doSomething(); });
Finally, the third way makes use of a self-executing function having jQuery as its sole parameter:
function doSomething() { return this; } (function($) { doSomething(); });
Implementation
For standard compliant browser, you can use the DOMContentLoaded
event directly:
addEventListener('DOMContentLoaded', handler);
For Internet Explorer, you can use this workaround:
if(document.body && document.body.lastChild) { // execute code }