Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top