Skip to content

Instantly share code, notes, and snippets.

@feross
Last active December 16, 2015 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feross/5513996 to your computer and use it in GitHub Desktop.
Save feross/5513996 to your computer and use it in GitHub Desktop.
Given a filename for a static resource, returns the resource's absolute URL. Supports file paths with or without origin/protocol.
/**
* Given a filename for a static resource, returns the resource's absolute
* URL. Supports file paths with or without origin/protocol.
*/
function toAbsoluteURL (url) {
// Handle absolute URLs (with protocol-relative prefix)
// Example: //domain.com/file.png
if (url.search(/^\/\//) != -1) {
return window.location.protocol + url
}
// Handle absolute URLs (with explicit origin)
// Example: http://domain.com/file.png
if (url.search(/:\/\//) != -1) {
return url
}
// Handle absolute URLs (without explicit origin)
// Example: /file.png
if (url.search(/^\//) != -1) {
return window.location.origin + url
}
// Handle relative URLs
// Example: file.png
var base = window.location.href.match(/(.*\/)/)[0]
return base + url
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment