Reply to comment

Still using $(document).ready in your jQuery scripts?

With the amount of jQuery tutorials being written, tweeted, and retweeted I keep seeing one common theme in nearly all of them. None of them use the jQuery shorthand to launch their scripts when their DOM is loaded.

Of course there's nothing wrong with this and it is perfectly valid, but if you are able to cut out code, that means you cut down on development. If you are familiar with jQuery then you're most likely familiar with starting your scripts like so:

$(document).ready(function() {
  //your code here
});

Well, after actually taking the time to read through some jQuery documentation, I've discovered an easier, although more abstract way of writing this:

$(function() {
  // your code here
});

That's all there is to it! You can get rid of (document).ready altogether. Enjoy!

UPDATE: The two methods are exactly the same, at least from what I can tell from my tests. The one exception is file size which saves 15 bytes or 16 bytes when gzipped. Special thanks to Kenneth (@ellisgl) for the test.

Reply

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><img>
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <css>, <drupal>, <java>, <javascript>, <mysql>, <php>, <ruby>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA

This question is for testing whether you are a human visitor and to prevent automated spam submissions.