Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JavaScript: handy hint for jQuery document ready handlers

DZone's Guide to

JavaScript: handy hint for jQuery document ready handlers

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Like 99% of all jQuery users, I write the code I want executed when the document is ready like this:

$(function () {
  // code using $ for the jQuery function
});

Except… What happens if someone calls $.noConflict() and $ is no longer valid? Do I have to resort to using jQuery() all over the place, just to be sure?

Answer: no. It seems – and I only discovered this moments ago – the document ready handler gets passed the jQuery function as the first and only argument. You can write this instead:

jQuery(function ($) {
  // code using $ for the jQuery function
});

Or, if you are really paranoid:

jQuery(function ($, undefined) {
  // code using $ as the jQuery function
  // and undefined means what it says
});

Magic!

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}