What's the difference between [removed] and [r

2018-12-31 16:26发布

Should both of them reference the same object?

16条回答
荒废的爱情
2楼-- · 2018-12-31 17:13

I would say window.location is the more reliable way of getting the current URL. Following is the difference between the window.location and document.url that came in front in one of the scenarios where I was appending hash parameters in the URL and reading it later.

After adding hash parameters in the URL.

In an older browser, I was not able to get the hash parameters from the URL by using document.url, but when I used window.location then I was able to get the hash parameters from the URL.

So it's always better to use window.location.

查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 17:14

Well yea, they are the same, but....!

window.location is not working on some Internet Explorer browsers.

查看更多
姐姐魅力值爆表
4楼-- · 2018-12-31 17:15

According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location rather than document.location.

See: http://www.w3.org/TR/html/browsers.html#dom-location

查看更多
查无此人
5楼-- · 2018-12-31 17:15

Despite of most people recommend here, that is how Google Analytics's dynamic protocol snipped looked like for ages (before they moved from ga.js to analytics.js recently):

ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

More info: https://developers.google.com/analytics/devguides/collection/gajs/

In new version they used '//' so browser can automatically add protocol:

'//www.google-analytics.com/analytics.js'

So if Google prefers document.location to window.location when they need protocol in JS, I guess they have some reasons for that.

OVERALL: I personally believe that document.location and window.location are the same, but if giant with biggest stats about usage of browsers like Google using document.location, I recommend to follow them.

查看更多
登录 后发表回答