【发布时间】:2016-04-30 01:58:59
【问题描述】:
这周我在清理一些旧的 JavaScript 代码时发生了一件有趣的事情。当我取出一些慢代码时,页面开始在通过 Ajax 调用包含的文件中的代码上抛出引用错误。
以下是该问题的(非常简化的)示例。直接请求时,第一个文件将正常工作。但是当通过 Ajax 调用时,document-ready 事件已经发生,因此其中的代码会立即执行。 Chrome 抛出错误如:“VM1414:2 Uncaught ReferenceError: they_log is not defined”
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.js"></script>
<script>
$(document).ready(function() {
they_log("Be alerted");
});
</script>
<!-- Two separate script tags prevent hoisting -->
<script>
function they_log($string) {
console.log($string);
}
</script>
</body>
</html>
但是,如果下面的注释“alert”行未注释,则不会在 Chrome 或 Firefox 中引发参考错误(尽管它们仍会在 Safari 中发生 - 除非您让模式对话框挂起几秒钟)。
<!doctype html>
<html lang="en">
<head>
<title>Prototype of reference error issue</title>
</head>
<body>
<div id="place" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.js"></script>
<script>
$.get( "http://localhost/path/to/first/file.html", function( data ) {
$("#place").html(data);
});
//alert("I get rid of the reference error");
</script>
</body>
</html>
我的问题是,警报消息(或包含文件中的类似慢代码)如何防止发生引用错误?
我特别感兴趣的是,无论发生什么让代码执行时不会出错,都可以指望它能够始终如一地工作(至少在 Chrome 和 Firefox 中),或者如果出现类似竞态条件的情况,它可能会失败间歇性的。
【问题讨论】:
标签: javascript