jQuery文档ready()函数花费很长时间执行的可能性 [英] possibility of jQuery document ready() function taking a very long time to execute
问题描述
我的问题是,有时候一段JavaScript(通常是Google Analytics)可能需要很长时间才能加载,但HTML准备好被穿越和操纵并不重要。如果我使用下面的代码:
$(document).ready(function(){
$( (DOM现在被加载并且可以被操纵。);
});
是否意味着< p>
直到Google Analytics(分析)加载之后才会被填充?
大多数网站通常不需要Google Analytics(分析),我经常发现我正在等待它加载。 (我不想使用onload,因为不可靠)。
有没有更好的方法或者说不要等待[...]的方法?
注意:我通常无法将代码放在< / body>
标记之前的< script>
标记中因为该网站基于模板。我通常只能编辑页面的内容。
Google实际上已经发布了他们称之为异步跟踪:
< 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>
解决了这个问题,因为它只会在解析DOM时加载,因此您可以使用所有东西在页面上。
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.
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.
这篇关于jQuery文档ready()函数花费很长时间执行的可能性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!