Skip to content

Instantly share code, notes, and snippets.

@teodragovic
Last active July 18, 2016 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teodragovic/6a3c498e0eedf4236b916e6a7ec0b510 to your computer and use it in GitHub Desktop.
Save teodragovic/6a3c498e0eedf4236b916e6a7ec0b510 to your computer and use it in GitHub Desktop.
Check for onload event in async scripts
(function(d) {
/**
* asyncOnLoad - Initilize all functions that depend on document.ready
* Since we load script async we must check if document already loaded or listen for DOMContentLoaded event.
* @param {Function} cb - callback function - put all stuff that must run here
*/
var asyncOnLoad = function(cb) {
// cut the mustard
if ('addEventListener' in d) {
if (d.readyState !== "loading") {
cb();
} else {
d.addEventListener('DOMContentLoaded', cb);
}
} else {
console.log('browser not supported!');
}
};
// commonjs
if (typeof module !== 'undefined') {
module.exports = asyncOnLoad;
} else {
window.asyncOnLoad = asyncOnLoad;
}
})(document);
function test(str) {
console.log(str);
}
// Init stuff
asyncOnLoad(function() {
test('hello world');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment