Skip to content

Instantly share code, notes, and snippets.

@andergmartins
Created September 28, 2012 03:59
Show Gist options
  • Save andergmartins/3797854 to your computer and use it in GitHub Desktop.
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.
/**
* 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);
}
@andergmartins
Copy link
Author

Can trigger an issue if the script moved to the end has a document.write() statement...

@andergmartins
Copy link
Author

But it isn't a bug... is the way document.write works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment