scriptloader.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. function ScriptLoader() {
  2. var self = this;
  3. this.scriptCache = [];
  4. this.loadingScripts = [];
  5. this.finishedCallback = function() {};
  6. this.isAlreadyLoaded = function(scriptPath) {
  7. return this.scriptCache.indexOf(scriptPath) != -1;
  8. };
  9. this.attach = function(scriptPath) {
  10. if(this.isAlreadyLoaded(scriptPath)) {
  11. return;
  12. }
  13. var domElement = document.createElement("script");
  14. domElement.src = scriptPath;
  15. domElement.type="text/javascript";
  16. domElement.async = true;
  17. domElement.addEventListener('load', function(event){
  18. if(self.loadingScripts.indexOf(scriptPath) != -1) {
  19. self.loadingScripts.splice(self.loadingScripts.indexOf(scriptPath), 1);
  20. }
  21. if(self.loadingScripts.length == 0) {
  22. self.finishedCallback();
  23. }
  24. });
  25. this.loadingScripts.push(scriptPath);
  26. document.getElementsByTagName("body")[0].appendChild(domElement);
  27. this.scriptCache.push(scriptPath);
  28. };
  29. this.finishedLoading = function(callback) {
  30. this.finishedCallback = callback;
  31. }
  32. };
  33. var loader = new ScriptLoader();
  34. var include = function(scriptPath) {
  35. loader.attach(scriptPath);
  36. };