jQuery $(document).ready() shorthand - domready

Posted by Ronald Eddy on Friday, October 10, 2014

jQuery .ready()

JavaScript provides the load event for executing code when a page is rendered. This event gets triggered when the download assets such as images has completed. However, most people want their script to run as soon as the DOM hierarchy has been fully constructed. jQuery provides the .ready() for just this purpose. This is the corresponding domready function in Mootools.

$(document).ready() Example
}$(document).ready(function() {
  // your code
  alert('Page: ' + $('title').html() + ' dom loaded!');
});
$(function() {…}); Example
$(function() {
 // Handler for .ready() called.
 alert('Page: ' + $('title').html() + ' dom loaded!');
});

Prevent jQuery Conflicts

To prevent conflicts, it is recommend to do the following:

  1. aliasing the jQuery namespace.
  2. call $.noConflict() to avoid namespace difficulties (as the $ shortcut is no longer available)
  3. Use the jQuery each time it jQuery required.
jQuery.noConflict() Example
jQuery.noConflict();
(function($) { 
  $(function() {
   // by passing the $ you can code using the $ alias for jQuery
   alert('Page: ' + $('title').html() + ' dom loaded!');
  });
})(jQuery);

.ready() Handler

The handler passed to .ready() is guaranteed to be executed after the DOM is ready. This is usually the best place to attach all other event handlers and run other jQuery code. If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.

Read more: jQuery Learning Center


comments powered by Disqus