admin管理员组

文章数量:1187336

I'm using some external jQuery with $(document).ready() to insert adverts after the document ready event has fired, something like:

$(document).ready( function() {
  $('#leaderboard').html("<strong>ad code</strong>");     
});

This is to prevent the UI being blocked by the slow loading of the adverts. So far it's been working well.

Now I need to insert some more ads though our CMS system, this can't be part of the external JS file, so I'm wondering can I use a second document ready event and insert it using an inline script tag? If so, what will be the order of execution the external JS document ready event first or the inline script?

I'm using some external jQuery with $(document).ready() to insert adverts after the document ready event has fired, something like:

$(document).ready( function() {
  $('#leaderboard').html("<strong>ad code</strong>");     
});

This is to prevent the UI being blocked by the slow loading of the adverts. So far it's been working well.

Now I need to insert some more ads though our CMS system, this can't be part of the external JS file, so I'm wondering can I use a second document ready event and insert it using an inline script tag? If so, what will be the order of execution the external JS document ready event first or the inline script?

Share Improve this question edited Jul 11, 2011 at 10:31 geekQ 29.5k13 gold badges63 silver badges58 bronze badges asked Apr 17, 2009 at 10:00 TomTom 34.4k31 gold badges89 silver badges111 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 10

You can use as many event methods as you want, jquery joins them in a queue. Order of method call is same as definition order - last added is last called.

A useful thing may be also that, you can load html code with script using ajax and when code is loaded into DOM $().ready() also will be called, so you can load ads dynamically.

Yes, adding multiple $(documents).ready()s is not a problem. All will be executed on the ready event.

Note however that your code sample is wrong. $(document).ready() takes a function, not an expression. So you should feed it a function like this:

 $(document).ready( function() {
  $('#leaderboard').html("<strong>ad code</strong>");     
 });

That function will be executed when the document is ready.

Here's a little tutorial on Multiple Document Ready

An added bonus of the jQuery way is that you can have multiple ready() definitions. This is the case with all jQuery events.

$(document).ready(function () { alert("Number One"); });

$(document).ready(function () { alert("Number Two");

JQuery calls the ready functions in the order they are defined. If you want to load some data first and deleay execution use holdReady().

本文标签: javascriptsecond (document)ready event jQueryStack Overflow