Skip to content Skip to sidebar Skip to footer

Why Do I Need To Add $(document).ready To A Self-executing Function?

I'm just messing with some javascript and I came across something that puzzled me a little. I've added a link to a script file into the header of a document, just after the link t

Solution 1:

I've added a link to a script file into the header of a document

This is the point.

Usually people put script files in the footer of document to optimize the process of loading the page, therefore it would not need to wait for the document to be ready to execute something based on the DOM already loaded (if you are in the footer, you have already loaded the rest - unless you have some content loading async).

Try putting your script file in the footer, and you will not need the $(document).ready.

Summary: In your case you need it, because when the script starts executing you have not started yet looking for the DOM, and the element cannot be found in that time.

Solution 2:

It's because document ready waits until the document has fully loaded before executing.

Anything that binds to DOM elements must be done when the document is fully loaded otherwise those event handler bindings will be trying to bind to DOM elements which don't yet exist.

So yes, you answered your own question.

Solution 3:

$( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute

It waits for the entire HTML excepts the Images. some times you noticed that you recived an error “$ is not defined.” then in that case you can use $( document ).ready()

Solution 4:

You can just move the $ to make it work

$(function(){


$("#thing").mouseover(function(){alert("woo");});


});

Demo

Explanation $(function(){}); is equivalent to $(document).ready(function(){}); in jQuery

Solution 5:

The document ready function waits for the page to load and then executes whatever is in there. This prevents immature actions before the page loads. As a thumb rule, remember this,

$(document).ready(function(){

  //jQuery code goes here

});

Post a Comment for "Why Do I Need To Add $(document).ready To A Self-executing Function?"