Created
April 5, 2011 18:55
-
-
Save NathanGRomano/904251 to your computer and use it in GitHub Desktop.
lazy loading example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>LazyLoading Test</title> | |
<script> | |
var AsyncLoader = function(src, cb) { | |
var s = document.createElement('script'); | |
s.type = 'text/javascript'; | |
s.async = true; | |
s.src = src + '?=' + Math.random(); // make sure we are loading this once | |
if(typeof(cb) == 'function') { | |
this.onLoad(cb); | |
} | |
var onLoad = this.onLoad(); | |
s.onreadystatechange = function() { | |
if(this.readyState == 'loaded' || | |
this.readyState == 'complete') { | |
onLoad(); | |
} | |
}; | |
s.onload = onLoad; | |
s.onerror = onLoad; | |
var asyncLoad = function() { | |
setTimeout(function() { | |
document.getElementById('msg').innerHTML = document.getElementById('msg').innerHTML + 'Loading...'; | |
var x = document.getElementsByTagName('script')[0]; | |
var head = document.getElementsByTagName("head")[0]; | |
x.parentNode.insertBefore(s, x); | |
}, 1000); | |
}; | |
if (window.attachEvent) { | |
window.attachEvent('onload', asyncLoad); | |
} else if(window.addEventListener) { | |
window.addEventListener('load', asyncLoad, false); | |
} | |
}; | |
AsyncLoader.prototype.onLoad = function(cb) { | |
if(typeof(cb) == 'function') { | |
this._cb = cb; | |
} else if(typeof(this._cb) == 'function') { | |
var that = this; | |
return function() { | |
that._cb(); | |
} | |
} | |
}; | |
var loader = new AsyncLoader('http://www.mersenneforum.org/txt/43.txt', function() { | |
document.getElementById('msg').innerHTML = document.getElementById('msg').innerHTML + 'done'; | |
}); | |
</script> | |
</head> | |
<body> | |
<h1>Javascript Lazy Loading Test</h1> | |
<div id='msg'></div> | |
<div style="height:1000px; width: 50px; background: #aaaaaa;"></div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment