在处理缺陷时,我遇到了与我的理解不同的 window.location 行为。在此问题之前,我相信为 赋值window.location 将阻止其他操作并继续重定向。
// Try to answer the questions before you run this script on JSFiddle.
// 1. Which site is going to load as a result of redirect method - apple.com or mashable.com?
// 2. Will the console log 'script added' print in console?
function redirect(url) {
var el = document.createElement('script');
var head = document.getElementsByTagName("head")[0];
var content = "window.location.href='"+url+"'";
el.innerHTML = content;
head.appendChild(el);
}
console.log('adding scripts');
redirect('http://apple.com');
redirect('http://mashable.com');
console.log('script added');
我试图寻找解释这种行为的文档,但找不到任何文档。任何详细解释 window.location 的文档或文章都会很有用。
最佳答案
在 Javascript 中,设置 window.location.href
一般是非阻塞操作。
在 DNS 解析新页面时,您仍然可以运行 Javascript 操作。因此,如果您更改 location.href
在此之前,您将重新开始该过程。
您可以阅读如何window.location
(特别是 window.location.assign
)预计将在 处的 Javascript 中执行WHATWG: Living HTML - HTML Standard.
当window.location
对象设置后,Web 浏览器将启动 Location-object navigate
或 Location-object-setter navigate
子程序。
关于javascript - window.location 是非阻塞操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34030245/