Introduction
Introduction Statistics Contact Development Disclaimer Help
loadscript: simplify and improve script loading - jscancer - Javascript crap (r…
git clone git://git.codemadness.org/jscancer
Log
Files
Refs
README
LICENSE
---
commit 8803e0fdca023fa927652585137eb5607355e357
parent 76a6ab53c42092f2e4a7d7229b0268cc8fd33fd4
Author: Hiltjo Posthuma <[email protected]>
Date: Sun, 2 Oct 2016 13:19:16 +0200
loadscript: simplify and improve script loading
- change check if loaded: don't keep global table (can be implemented separatel…
- simplify check if all scripts are loaded: scripts_load.
- add comment for IE workaround logic.
- simplify example.
Diffstat:
M loadscript/example.html | 5 ++---
M loadscript/loadscript.js | 29 +++++++++++++----------------
2 files changed, 15 insertions(+), 19 deletions(-)
---
diff --git a/loadscript/example.html b/loadscript/example.html
@@ -8,13 +8,12 @@
<script type="text/javascript">
var el = document.getElementById("test");
-el.addEventListener("click", function() {
+el.onclick = function() {
scripts_load(["example_load.js"], function() {
test_init();
});
// this.style.display = "none"; // hide button.
- el.removeEventListener("click", this);
-});
+};
</script>
</body>
</html>
diff --git a/loadscript/loadscript.js b/loadscript/loadscript.js
@@ -1,19 +1,17 @@
-var script_loaded = {};
-
function script_load(uri, fn) {
- // load script once.
- if (script_loaded[uri] !== undefined)
- return;
var script = document.createElement("script");
script.type = "text/javascript";
script.src = uri;
script.async = true;
+ var loaded = 0;
var onload = function() {
- if (script_loaded[uri] === undefined) {
- script_loaded[uri] = true;
+ // fire fn() once.
+ if (!loaded) {
+ loaded = 1;
fn();
}
};
+ // for IE <= 8.
script.onreadystatechange = function() {
switch (this.readyState) {
case "complete":
@@ -21,20 +19,19 @@ function script_load(uri, fn) {
onload();
}
}
+ // for the normal world.
script.onload = function() {
onload();
};
document.getElementsByTagName("head")[0].appendChild(script);
}
-// load list of uri's, fire fn() when all are loaded.
+// load list of uri's (async, order indetermined), fire fn() when all
+// are loaded.
function scripts_load(uris, fn) {
- var checkfn = function() {
- for (var i = 0; i < uris.length; i++)
- if (script_loaded[uris[i]] === undefined)
- return; // not all scripts are loaded.
- fn();
- };
- for (var i = 0; i < uris.length; i++)
- script_load(uris[i], checkfn);
+ for (var i = 0, loaded = 0; i < uris.length; i++)
+ script_load(uris[i], function() {
+ if (++loaded == uris.length)
+ fn();
+ });
}
You are viewing proxied material from codemadness.org. The copyright of proxied material belongs to its original authors. Any comments or complaints in relation to proxied material should be directed to the original authors of the content concerned. Please see the disclaimer for more details.