Skip to content

Instantly share code, notes, and snippets.

@danshearmur
Last active August 29, 2015 14:11
Show Gist options
  • Save danshearmur/bb53650bfc46a3b90268 to your computer and use it in GitHub Desktop.
Save danshearmur/bb53650bfc46a3b90268 to your computer and use it in GitHub Desktop.
<!doctype html>
<script>
var cache = {};
function define(thing, fn) {
cache[thing] = fn;
}
function load(file) {
var s = document.createElement('script');
s.src = file;
var callback;
s.onreadystatechange = s.onload = function () {
if (s.readyState) {
if (s.readyState === "loaded" || s.readyState === "complete") callback(cache[file]);
} else {
if (callback) callback(cache[file]);
}
};
var ref = document.querySelector('script');
ref.parentNode.insertBefore(s, ref);
return {
then: function (cb) {
if (cache[file]) return cb(cache[file]);
callback = cb;
}
};
}
</script>
<script>
var start = performance.now();
load('wrapper.js').then(function (cb) {
console.log('define: load time %f', performance.now() - start);
cb();
console.log('define: exec time %f', performance.now() - start);
});
</script>
<!doctype html>
<iframe src="xhr.html"></iframe>
<iframe src="define.html"></iframe>
var x = Math.random() * 1000;
console.log(x);
define('wrapper.js', function () {
var x = Math.random() * 1000;
console.log(x);
});
<!doctype html>
<script>
function load(file) {
var x = new XMLHttpRequest();
var script;
var callback;
x.onreadystatechange = function () {
if (x.readyState !== 4) return;
script = function () { eval(x.responseText); };
if (callback) callback(script);
};
x.open("GET", file, true);
x.send();
return {
then: function (cb) {
if (script) cb(script);
callback = cb;
}
};
}
</script>
<script>
var start = performance.now();
load('plain.js').then(function (cb) {
console.log('xhr: load time %f', performance.now() - start);
cb();
console.log('xhr: exec time %f', performance.now() - start);
});
</script>
@danshearmur
Copy link
Author

So eval is loads faster :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment