Skip to content

Instantly share code, notes, and snippets.

@dhigginbotham
Created February 19, 2014 17:18
Show Gist options
  • Save dhigginbotham/9096744 to your computer and use it in GitHub Desktop.
Save dhigginbotham/9096744 to your computer and use it in GitHub Desktop.
alternative dom.ready and dom.load events
(function(root, doc) {
/**
* dom.ready.js is a tiny library
* to help with cross-browser compatible
* `DOMContentLoaded` (dom ready)
* event binding
*
* author: dhigginbotham
* license: MIT
* browser support: [IE8+, FF, Chrome]
*/
/**
* ready object for global space
*/
var dom = {};
/**
* privates
*/
var priv = {};
/**
* internal loadEvents, separated by their
* browser
*/
priv.loadEvents = {
modern: 'DOMContentLoaded',
ie: 'readystatechange'
};
/**
* internal regex, initializing it here
* saves some memory overall
*/
priv.regex = {
gecko: /gecko/i
};
/**
* fairly simple device check
*/
priv.getClientBrowser = function() {
if (typeof root.navigator != 'undefined' && root.navigator.appName) {
return (root.appName != priv.regex.gecko ? 'ie' : 'modern');
} else return 'ie';
};
/**
* internal event listener
*/
priv.internalEventListener = function(element, eventName, fn) {
if (element.addEventListener) {
return element.addEventListener(eventName, fn, false);
} else if (element.attachEvent) {
return element.attachEvent("on" + eventName, fn);
};
};
/**
* dom.ready function, accepts a
* single callback function to fire
*/
dom.ready = function(fn) {
var ev;
if (priv.getClientBrowser() == 'ie') {
ev = priv.loadEvents.ie;
} else {
ev = priv.loadEvents.modern;
}
return priv.internalEventListener(doc, ev, fn);
};
/**
* dom.load, loads onto window.load
*/
dom.load = function(fn) {
var ev = 'load';
return priv.internalEventListener(root, ev, fn);
};
/**
* make it accessible outside of the closure
*/
if (typeof module != 'undefined' && module.exports) {
module.exports = dom;
} else {
root.dom = dom;
}
})(window, document);
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>dom.ready.js</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="ready"></div>
<div id="load"></div>
<script type="text/javascript" src="dom.js"></script>
<script>
var startTime = Date.now();
dom.ready(function () {
var el = document.getElementById('ready');
el.innerText = 'ready in ' + (Date.now() - startTime) + 'ms';
});
dom.load(function () {
var el = document.getElementById('load');
el.innerText = 'load in ' + (Date.now() - startTime) + 'ms';
});
</script>
</body>
</html>
@6eDesign
Copy link

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