When doing AJAX request in JavaScript, is there any case where it could be necessary to write
window.location.protocol + '//' + window.location.host
instead of simply
/
After all, files like images, scripts, and css are always specified relative so it should be the same when making ajax requests.
The reason I’m asking this is because I can’t find any official suggestion (e.g. from w3c) on how to do it.
They’re not strictly the same, as
window.location.protocol + '//' + window.location.hostis missing the trailing slash to indicate the root directory. But for all intents and purposes, they can be used interchangeably.In practical usage, assuming you’re not using
<base>, all of the following will point to the same place:window.location.hostcontains the port number if it’s anything other than 80, so you shouldn’t have to worry about including that. It’s simpler and clearer to write'/', as it always means “the root directory of whichever server this page came from.” Things could get hairy if the URI contains something likeusername:password@— I don’t know of a way to get that data using JS. Trying to reassemble a URI from individual components could cause problems if the code is migrated to an unusual environment like that.The formal definition for all of this is in RFC3986, which is not exactly light reading.