Reputation: 144927
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.
Upvotes: 3
Views: 6999
Reputation: 3622
In most modern browsers you can now write:
<script>var _gaq = _gaq || [["_setAccount","UA-XXXXX-X"],["_trackPageview"]]; </script>
<script src="//www.google-analytics.com/ga.js" async></script>
The script will load async on most browsers, and cope with different schemes automagically..
You might like to use the longer - safer for older browsers - version:
<script>var _gaq = _gaq || [["_setAccount","UA-XXXXX-X"],["_trackPageview"]]; </script>
<script type="text/javascript" src="//www.google-analytics.com/ga.js" async="true" defer="true"></script>
A few cavets:
Upvotes: 1
Reputation:
I had the same issue. Just put this line at first javascript load and it works fine on IE after that:
jQuery.noConflict();
Upvotes: -2
Reputation: 144927
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.
Upvotes: 5
Reputation: 121294
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.
Upvotes: -1
Reputation: 532445
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.
Upvotes: 6