views:

1697

answers:

4

My issue is that sometimes a piece of JavaScript (often Google Analytics) may take a very long time to load, although it's not important to the HTML be ready to be "traversed and manipulated". If I were to use the following code:

$(document).ready(function () {
    $("p").text("The DOM is now loaded and can be manipulated.");
});

would this mean that the <p> would not be populated till after something like Google Analytics is loaded?

Something like Google Analytics is generally not required on most websites and I have often found that I am waiting for it to load. (I don't want to use onload because of it's unreliability.)

Is there a better way or a way to say "don't wait for [...]"?

Note: I usually cannot put the code in a <script> tag just before the </body> tag because the site is based in a template. I usually can only edit the "content" of the page.

+4  A: 

Have you tried loading Google analytics from within the ready function? Here's a link that discusses dynamic script loading. Presumably you'd do this at the end after the other parts of your ready script had already executed.

tvanfosson
A: 

This is just a guess but have you considered setTimeOut()?

$(document).ready(function()
{
   setTimeOut(function()
   {
      // Your code comes here
   }, 0); // We don't really need any delay
});

setTimeOut() has the nice feature of escaping the call stack, so it might solve your problem.

DrJokepu
A: 

i have the same issue... just try to put this line at first java load and it load fine on IE after that...

jQuery.noConflict();

I don't think that will work...that's for a different purpose.
Darryl Hein
+2  A: 

Google has actually released what they're calling Asynchronous Tracking:

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
  })();

</script>

This solves the problem because it will only load once the DOM is parsed and therefore you can already use everything on the page.

Darryl Hein