initial script to load other scripts on-demand - jscancer - Javascript crap (re… | |
git clone git://git.codemadness.org/jscancer | |
Log | |
Files | |
Refs | |
README | |
LICENSE | |
--- | |
commit a483eaff4722585813a1e64dedde3fa3d2e66b4a | |
parent 44c57648b8d5f8ecc939bec21affe6fb7c1fec62 | |
Author: Hiltjo Posthuma <[email protected]> | |
Date: Sun, 29 May 2016 13:26:19 +0200 | |
initial script to load other scripts on-demand | |
Diffstat: | |
A loadscript/example.html | 18 ++++++++++++++++++ | |
A loadscript/example_load.js | 3 +++ | |
A loadscript/loadscript.js | 28 ++++++++++++++++++++++++++++ | |
3 files changed, 49 insertions(+), 0 deletions(-) | |
--- | |
diff --git a/loadscript/example.html b/loadscript/example.html | |
@@ -0,0 +1,18 @@ | |
+<html> | |
+<head> | |
+<script type="text/javascript" src="loadscript.js"></script> | |
+</head> | |
+<body> | |
+<input type="button" id="test" /> | |
+ | |
+<script type="text/javascript"> | |
+var el = document.getElementById("test"); | |
+el.onclick = function() { | |
+ script_load("example_load.js", function() { | |
+ test_init(); | |
+ }); | |
+ this.style.display = "none"; // hide button. | |
+}; | |
+</script> | |
+</body> | |
+</html> | |
diff --git a/loadscript/example_load.js b/loadscript/example_load.js | |
@@ -0,0 +1,3 @@ | |
+function test_init() { | |
+ alert("plop"); | |
+} | |
diff --git a/loadscript/loadscript.js b/loadscript/loadscript.js | |
@@ -0,0 +1,28 @@ | |
+var script_loaded = {}; | |
+function script_load(uri, fn) { | |
+ // load script once. | |
+ if (script_loaded[uri] !== undefined) | |
+ return; | |
+ fn = fn || function() {}; | |
+ script_loaded[uri] = { | |
+ "fn": function() { | |
+ // execute function once. | |
+ fn(); | |
+ script_loaded[uri].fn = function() {}; | |
+ } | |
+ }; | |
+ var script = document.createElement("script"); | |
+ script.type = "text/javascript"; | |
+ script.src = uri; | |
+// script.onreadystatechange = function() { | |
+// switch (this.readyState) { | |
+// case "complete": | |
+// case "loaded": | |
+// script_loaded[uri].fn(); | |
+// } | |
+// } | |
+ script.onload = function() { | |
+ script_loaded[uri].fn(); | |
+ }; | |
+ document.head.appendChild(script); | |
+} |