Last active
July 18, 2016 11:19
-
-
Save teodragovic/6a3c498e0eedf4236b916e6a7ec0b510 to your computer and use it in GitHub Desktop.
Check for onload event in async scripts
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
(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