jQuery document ready()函数可能需要很长时间才能执行

Dar*_*ein 3 jquery google-analytics onload

我的问题是,有时候一段JavaScript(通常是谷歌分析)可能需要很长时间才能加载,尽管HTML已经准备好"遍历和操纵"并不重要.如果我要使用以下代码:

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

这是否意味着在<p>加载Google Analytics之类的东西之前不会填充?

大多数网站通常不需要像Google Analytics这样的东西,我经常发现我正在等待它加载.(我不想使用onload,因为它不可靠.)

是否有更好的方式或方式来说"不要等待[...]"?

注意:我通常无法将代码放在<script>标记之前的</body>标记中,因为该网站基于模板.我通常只能编辑页面的"内容".

tva*_*son 6

您是否尝试在ready函数中加载Google Analytics?这是一个讨论动态脚本加载的链接.据推测,在准备好的脚本的其他部分已经执行之后,你最终会这样做.


Dar*_*ein 5

谷歌实际上发布了他们称之为异步跟踪的东西:

<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>
Run Code Online (Sandbox Code Playgroud)

这解决了这个问题,因为它只会在解析DOM后加载,因此您已经可以使用页面上的所有内容.