Skip to content

Instantly share code, notes, and snippets.

@paranoidjk
Created November 21, 2016 10:01
Show Gist options
  • Save paranoidjk/6e11f272b2a0383c62004302ae0cf3db to your computer and use it in GitHub Desktop.
Save paranoidjk/6e11f272b2a0383c62004302ae0cf3db to your computer and use it in GitHub Desktop.
contentloaded.js
/*!
* contentloaded.js
*
* Author: Diego Perini (diego.perini at gmail.com)
* Summary: cross-browser wrapper for DOMContentLoaded
* Updated: 20101020
* License: MIT
* Version: 1.2
*
* URL:
* http://javascript.nwbox.com/ContentLoaded/
* http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE
*
*/
// @win window reference
// @fn function reference
function contentLoaded(win, fn) {
var done = false, top = true,
doc = win.document,
root = doc.documentElement,
modern = doc.addEventListener,
add = modern ? 'addEventListener' : 'attachEvent',
rem = modern ? 'removeEventListener' : 'detachEvent',
pre = modern ? '' : 'on',
init = function(e) {
if (e.type == 'readystatechange' && doc.readyState != 'complete') return;
(e.type == 'load' ? win : doc)[rem](pre + e.type, init, false);
if (!done && (done = true)) fn.call(win, e.type || e);
},
poll = function() {
try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; }
init('poll');
};
if (doc.readyState == 'complete') fn.call(win, 'lazy');
else {
if (!modern && root.doScroll) {
try { top = !win.frameElement; } catch(e) { }
if (top) poll();
}
doc[add](pre + 'DOMContentLoaded', init, false);
doc[add](pre + 'readystatechange', init, false);
win[add](pre + 'load', init, false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment