Last active
December 16, 2015 23:29
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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