Should both of them reference the same object?
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.
document.location === window.location
returns true
also
document.location.constructor === window.location.constructor
is true
Note: Just tested on , Firefox 3.6, Opera 10 and IE6
As far as I know, Both are same. For cross browser safety you can use window.location
rather than document.location
.
All modern browsers map document.location
to window.location
, but I still prefer window.location
as that's what I've used since I wrote my first web page. it is more consistent.
you can also see document.location === window.location
returns true
, which clarifies that both are same.
The canonical way to get the current location object is window.location
(see this MSDN page from 1996 and the W3C draft from 2006).
Compare this to document.location
, which originally only returned the current URL as a string (see this page on MSDN). Probably to avoid confusion, document.location
was replaced with document.URL
(see here on MSDN), which is also part of DOM Level 1.
As far as I know, all modern browsers map document.location
to window.location
, but I still prefer window.location
as that's what I've used since I wrote my first DHTML.
At least in IE, it has a little difference on local file:
document.URL will return "file://C:\projects\abc\a.html"
but window.location.href will return "file:///C:/projects/abc/a.html"
One is back slash, one is forward slash.
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
.