0

在我的网页中,我有这样的脚本:

<head>
<script src="scripts/effect.js"></script>
<script>
if (document.readyState == 'complete') {
  doOnLoad();
}
$(window).bind("load", doOnLoad);
function doOnLoad() {
    console.log("here..");
}
</script>
</head>

effect.js文件包含如下所示的脚本:

$( document ).ready(function(){
    console.log("yes");
   // here I've script for reading a text file using ajax and manipulating the result from text file
    $.ajax({
      // code goes here
      console.log("ajax");
    });
});

问题是当我最初运行页面时,我没有得到结果。那时我得到控制台输出为

yes
here..
ajax

但是当我再次刷新页面时,我得到的结果和控制台打印如下:

yes
ajax
here..

window.load完成后如何运行document.ready

谁能帮我解决这个问题?提前致谢。

4

1 回答 1

0

这都是关于脚本执行的时间。听起来一旦加载和缓存某些资源,行为就会发生变化。

您拥有的第一段代码有点令人困惑:

if (document.readyState == 'complete') {
    doOnLoad();
}

我不确定你为什么需要这个以及负载处理程序?无论如何,该条件似乎永远不会等于 true,因为该代码将在文档完成加载之前立即运行。至少,我会在这个块中放置一个console.log,这样我就可以确定是什么触发了doOnLoad。

尝试将页面上的脚本替换为以下内容:

$(window).on("load", doOnLoad);
function doOnLoad() {
    console.log("here..");
}
于 2016-10-28T11:35:55.167 回答