Last active
August 29, 2015 14:10
-
-
Save patrixd/52c389b7bc55a0e48ef9 to your computer and use it in GitHub Desktop.
Basic loader - Loads a script only once
This file contains 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
loadedScript = {}; | |
loadingScript = {}; | |
pendingScriptSuccess = {}; | |
function loadScript (url, success, async) { | |
if(loadedScript[url]) { | |
success(); | |
return; | |
} | |
pendingScriptSuccess[url] = _.isArray(pendingScriptSuccess[url]) ? pendingScriptSuccess[url].push(success) : [success]; | |
if(loadingScript[url]) { | |
return; | |
} | |
loadedScript[url] = false; | |
loadingScript[url] = true; | |
async = async || true; | |
$.ajax({ | |
crossDomain: true, | |
dataType: "script", | |
url: url, | |
async: async, | |
success: (function (url) { | |
return function (data) { | |
loadedScript[url] = true; | |
loadingScript[url] = false; | |
for (var i=0, len=pendingScriptSuccess[url].length; i<len; i++) { | |
if(pendingScriptSuccess[url][i]) | |
pendingScriptSuccess[url][i](data); | |
} | |
delete pendingScriptSuccess[url]; | |
}; | |
})(url) | |
}) | |
} |
This file contains 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
(function ($) { | |
//load dependencies | |
loadScript('underscore.js'); | |
//init when document loaded | |
$( window ).load(init); | |
})(jQuery); | |
function init () { | |
loadScript('underscore.js', function () { | |
//use underscore - underscore.js is loaded only once | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment