今天在 Firefox 中调试一些客户端 JavaScript 时,我遇到了一些我觉得很奇怪而且有点令人不安的事情。另外,在使用 IE / VS2010 调试相同的脚本时,我无法复制此行为。
我创建了一个简单的示例 html 文档来说明我所看到的异常情况。
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" type="text/javascript" ></script>
</head>
<body id="main_body">
<script type="text/javascript">
$(function () {
$(".test-trigger").on("click", function () {
loadStuff();
console && console.log && console.log("this will probably happen first.");
});
});
function loadStuff() {
$.get("http://google.com/")
.fail(function () {
console && console.log && console.log("this will probably happen second.");
});
}
</script>
<button class="test-trigger">test</button>
</body>
</html>
如果将此文档加载到 Firefox 中(我在 Windows 7 上使用版本 13.0 和 Firebug 版本 1.10.1),单击测试,然后查看 Firebug 中的控制台选项卡,您应该注意到 get 请求失败(跨域违规,与此无关)。处理我在这里试图表达的观点),然后你很可能会看到:
this will probably happen first.
this will probably happen second.
现在,在第 13 行和第 20 行放置断点:
13: console && console.log && console.log("this will probably happen first.");
20: console && console.log && console.log("this will probably happen second.");
如果再次单击测试,您将按预期在第 13 行中断。现在,恢复执行。如果您的经历和我一样,您将不会在第 20 行中断。此外,如果您切换到控制台选项卡,您将看到以下日志输出序列:
this will probably happen second.
this will probably happen first.
对我来说,这表明 ajax 请求的失败处理程序是在执行单击处理程序的线程之外的线程中执行的。我一直认为单个页面的所有 javascript 将由任何浏览器中的单个线程。我在这里错过了一些非常明显的东西吗?感谢您对此观察的任何见解。
哦,如果我使用 Visual Studio 调试在 IE 中运行的同一页面,两个断点都会按我的预期命中。