birgersp

include.js

Feb 6th, 2017
33
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2. * include.js
  3. * By Birger Skogeng Pedersen (birgersp)
  4. */
  5.  
  6. /**
  7. * Add a file to the list of script includes
  8. * @param {String} name
  9. */
  10. function include(name) {
  11.  
  12. var fixedName = (include.prefix + name).replace(/\/.*?\/\.\./g, "");
  13. if (include.files.indexOf(fixedName) === -1)
  14. include.files.push(fixedName);
  15. }
  16.  
  17. include.files = [];
  18. include.prefix = "";
  19.  
  20. // Initialize and start including
  21. (function () {
  22.  
  23. var headElement = document.getElementsByTagName("head")[0];
  24.  
  25. var mainScript;
  26. var scriptElements = document.getElementsByTagName("script");
  27. for (var i = 0; !mainScript && i < scriptElements.length; i++) {
  28. var script = scriptElements[i];
  29. if (script.hasAttribute("src") && script.hasAttribute("data-main"))
  30. mainScript = script.getAttribute("data-main");
  31. }
  32.  
  33. if (!mainScript)
  34. throw new Error("Main script not defined.");
  35.  
  36. var filesLoaded = 0;
  37. function loadScript(name) {
  38. include.prefix = "";
  39. var prefixNameSplit = name.split("/");
  40. var noOfPrefixes = prefixNameSplit.length - 1;
  41. for (var i = 0; i < noOfPrefixes; i++)
  42. include.prefix += prefixNameSplit[i] + "/";
  43.  
  44. var scriptElement = document.createElement("script");
  45. scriptElement.setAttribute("src", name + ".js");
  46. scriptElement.onload = function () {
  47. filesLoaded++;
  48. if (filesLoaded < include.files.length)
  49. loadScript(include.files[filesLoaded]);
  50. else {
  51. if (window.main === null || typeof window.main !== "function") {
  52. throw new Error("Could not invoke function \"main\"");
  53. }
  54. main();
  55. }
  56. };
  57. scriptElement.onerror = function (evt) {
  58. throw new Error("Could not load script \"" + name + ".js\"");
  59. };
  60. headElement.appendChild(scriptElement);
  61. }
  62.  
  63. include(mainScript);
  64. loadScript(mainScript);
  65. })();
RAW Paste Data