Created
September 28, 2012 03:59
-
-
Save andergmartins/3797854 to your computer and use it in GitHub Desktop.
Load external Javascript without blocking. Add an option to set a fallback URL, wich is loaded if the main URL fails.
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
/** | |
* scriptloader.js | |
* | |
* Script loader, specially for CDN fallback behavior. | |
* Adapted from Steve Souders code (thanks Steve) by | |
* Anderson G. Martins from Joomla Bamboo. | |
* | |
* Added the option to set a fallback URL, which will be used | |
* trying to load a local copy of the requested file. | |
* | |
* @author Steve Sourders | |
* @param String url URL where we find the script to load it. | |
* @param String fallbackURL The local URL that will be called if remote URL fails | |
* @param Function callback The function that will be called after complete loaded. | |
*/ | |
function loadScript(url, fallbackURL, callback) | |
{ | |
var script = document.createElement("script") | |
script.type = "text/javascript"; | |
if (script.readyState) // IE | |
{ | |
script.onreadystatechange = function() | |
{ | |
if (script.readyState == "loaded" || | |
script.readyState == "complete") | |
{ | |
script.onreadystatechange = null; | |
if (typeOf(callback) === 'function') | |
{ | |
callback(); | |
} | |
} | |
else if (script.readyState == "error") | |
{ | |
if (typeOf(fallbackURL) === 'string' && fallbackURL !== '') | |
{ | |
// Try to move forward with the fallback URL | |
loadScript(fallbackURL, null, callback); | |
} | |
} | |
}; | |
} | |
else // Others | |
{ | |
script.onload = function() | |
{ | |
if (typeOf(callback) === 'function') | |
{ | |
callback(); | |
} | |
}; | |
script.onerror = function() | |
{ | |
if (typeOf(fallbackURL) === 'string' && fallbackURL !== '') | |
{ | |
// Try to move forward with the fallback URL | |
loadScript(fallbackURL, null, callback); | |
} | |
} | |
} | |
script.src = url; | |
document.getElementsByTagName("head")[0].appendChild(script); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
But it isn't a bug... is the way document.write works