1

Example 1

Example 2

...Both of these use (from what I can tell) jquery's clone on a function block, as the outermost element of the script. Why is it done this way? What would be lost if that were omitted?

P.S. Is this like instantiating an object from a class?

Engineer
  • 8,529
  • 7
  • 65
  • 105

2 Answers2

6

It is needed to call the function when the document is ready. As of http://api.jquery.com/ready/

$(document).ready(function() {
  // Handler for .ready() called.
});

Which is equivalent to calling:

$(function() {
     // Handler for .ready() called.
});

that obviously is equal to

jQuery(function() {
  // Your code using failsafe $ alias here...
});

here jQuery is used instead in order to not conflict with $ in case it's used by another library.

KayakDave
  • 24,636
  • 3
  • 65
  • 68
steo
  • 4,586
  • 2
  • 33
  • 64
  • Ah, and for the purposes of backbone.js, this is necessary since, in each `Backbone.View`, when you declare `this.el` (the DOM element providing the basis of that `View`), the named element will not be defined until the DOM is ready, so you will otherwise end up with `this.el == undefined`. – Engineer Sep 08 '13 at 10:20
0

This is basically the DOMReady event. The function with your code is the code to be executed when the DOM is ready, but before all resources are loaded.

This ensures that all the HTML elements in your source code would be ready for manipulation in JS. Otherwise you may miss elements that are otherwise in your source code when trying to select them.

Attila Szeremi
  • 5,235
  • 5
  • 40
  • 64