窗口之间有什么区别。Location和document。Location ?它们是否都引用同一个对象?
当前回答
窗口。位置在所有兼容的浏览器上都是读/写的。
文档。location在Internet Explorer(至少)中是只读的,但在基于gecko的浏览器(Firefox, SeaMonkey)中是读/写的。
其他回答
根据W3C的说法,它们是相同的。实际上,为了跨浏览器的安全性,您应该使用window。Location而不是document.location。
见:http://www.w3.org/TR/html/browsers.html dom-location
我更喜欢使用文档。位置,尽管位置,文档。位置和窗口。Location返回相同的对象。
使用文件的原因。地点是:
窗口的浏览器兼容性部分。位置提到
在Firefox 57之前,通过URL api访问URL时,URL中包含的单引号会被转义。参见bug 1386683。
文档的浏览器兼容性部分。位置提到
全力支持。
Mdn location reference uses document.location in their examples. // location: https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container const loc = document.location; console.log(loc.href); // https://developer.mozilla.org:8080/en-US/search?q=URL#search-results-close-container console.log(loc.protocol); // https: console.log(loc.host); // developer.mozilla.org:8080 console.log(loc.hostname); // developer.mozilla.org console.log(loc.port); // 8080 console.log(loc.pathname); // /en-US/search console.log(loc.search); // ?q=URL console.log(loc.hash); // #search-results-close-container console.log(loc.origin); // https://developer.mozilla.org:8080 location.assign('http://another.site') // load another page
窗口。位置在所有兼容的浏览器上都是读/写的。
文档。location在Internet Explorer(至少)中是只读的,但在基于gecko的浏览器(Firefox, SeaMonkey)中是读/写的。
窗口。考虑到较老的浏览器,位置是两者中更可靠的一致性。
尽管大多数人在这里推荐,这就是谷歌Analytics的动态协议剪辑的样子(在他们最近从ga.js转移到analysis .js之前):
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
更多信息:https://developers.google.com/analytics/devguides/collection/gajs/
在新版本中,他们使用了'//',所以浏览器可以自动添加协议:
'//www.google-analytics.com/analytics.js'
如果谷歌更喜欢document。窗口的位置。当他们需要JS中的协议时,我猜他们有一些原因。
总的来说:我个人相信这份文件。位置和窗口。位置是相同的,但如果巨人与最大的统计使用浏览器像谷歌使用文档。地点,我建议遵循他们。