jQuery恼人的初始延迟

时间:2014-12-01 12:33:42

标签: jquery delay

我没有任何具体的代码可以显示,但是一般性的问题。每当我使用jQuery时,它在实际变为活动之前总是有1000-2000ms的延迟。我该如何解决这个问题?


示例

$(document).ready(function(){
    setInterval(function(){
        alert('This has been delayed more than necessary.');
    }, 1000);
}

它需要2000毫秒才能启动。我很长一段时间一直在努力解决这个问题,但我无法在网上找到答案。我已经搜索了Stack Overflow和Google。


提前致谢。

1 个答案:

答案 0 :(得分:0)

我不认为jQuery故意拖延代码的执行。这里有两层回调:

// here you are waiting for the HTML markup to finish being parsed
// and turned into a usable DOM (this is the "DOM-ready" event)
$(document).ready(function() {
    // This code does not run until the DOM is ready. Then, you delay
    // your alert by another 1 second by using this setInterval here
    setInterval(function(){
        // This will not happen for 1000ms after the DOM is ready
        alert('This has been delayed more than necessary.');
    }, 1000);
}

即使您的页面为空,您也要将代码延迟至少1秒钟。

其余部分可能是由于拥有大页面,加载许多脚本,大型CSS文件或字体文件。检查您的浏览器"网络"选项卡在其开发工具中查看页面加载的时间。

仅供参考,如果您将页面构建为最佳实践"它会看起来像这样:

<html>
<head>
    <script src="external/reference.js"></script>
</head>
<body>
    <!-- All your HTML are belong to us -->
    <script type="text/javascript">
        // put your code here, in a <script> tag right before the 
        // closing </body> tag
        alert('I'm ready!');
    </script>
</body>
</html>

...它不需要DOM-ready处理程序或setTimeout函数 - 它只是在页面的其余部分加载完毕后才会运行。