possibility of jQuery document ready() function taking a very long time to execute

跟風遠走 提交于 2019-12-04 14:11:45

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.

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.

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:

  • there's a bug in IE6 that will stop the JS from loading due to the missing protocol (see http://www.paulirish.com/2010/the-protocol-relative-url/) but you could just add the protocol you are using.
  • older browsers won't understand the "async" property so will load if either defered (after page loads) or just load it when they find it (so not async).

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.

I had the same issue. Just put this line at first javascript load and it works fine on IE after that:

jQuery.noConflict();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!