When should I use jQuery's document.ready func

2019-01-01 02:13发布

I was told to use document.ready when I first started to use Javascript/jQuery but I never really learned why.

Might someone provide some basic guidelines on when it makes sense to wrap javascript/jquery code inside jQuery's document.ready?

Some topics I'm interested in:

  1. jQuery's .on() method: I use the .on() method for AJAX quite a bit (typically on dynamically created DOM elements). Should the .on() click handlers always be inside document.ready?
  2. Performance: Is it more performant to keep various javascript/jQuery objects inside or outside document.ready (also, is the performance difference significant?)?
  3. Object scope: AJAX-loaded pages can't access objects that were inside the prior page's document.ready, correct? They can only access objects which were outside document.ready (i.e., truly "global" objects)?

Update: To follow a best practice, all my javascript (the jQuery library and my app's code) is at the bottom of my HTML page and I'm using the defer attribute on the jQuery-containing scripts on my AJAX-loaded pages so that I can access the jQuery library on these pages.

8条回答
不再属于我。
2楼-- · 2019-01-01 02:45

Before you can safely use jQuery you need to ensure that the page is in a state where it's ready to be manipulated. With jQuery, we accomplish this by putting our code in a function, and then passing that function to $(document).ready(). The function we pass can just be an anonymous function.

$(document).ready(function() {  
    console.log('ready!');  
});

This will run the function that we pass to .ready() once the document is ready. What's going on here? We're using $(document) to create a jQuery object from our page's document, and then calling the .ready() function on that object, passing it the function we want to execute.

Since this is something you'll find yourself doing a lot, there's a shorthand method for this if you prefer — the $() function does double duty as an alias for $(document).ready() if you pass it a function:

$(function() {  
    console.log('ready!');  
});  

This is a good reading: Jquery Fundamentals

查看更多
其实,你不懂
3楼-- · 2019-01-01 02:45

You should bind all actions in document.ready, because you should wait till the document is fully loaded.

But, you should create functions for all actions and call them from within the document.ready. When you create functions (your global objects), call them whenever you want. So once your new data is loaded and new elements created, call those functions again.

These functions are the ones where you've bound the events and action items.

$(document).ready(function(){
bindelement1();
bindelement2();
});

function bindelement1(){
$('el1').on('click',function...);
//you might make an ajax call here, then under complete of the AJAX, call this function or any other function again
}

function bindelement2(){
$('el2').on('click',function...);
}
查看更多
登录 后发表回答