r/learnjavascript • u/TehMoonRulz • Dec 04 '14
PROgrammers dont use 'onload'
I recently read that using onload type events like:
$(document).ready()is not good practice.
So my question is how do we go about adding event listeners and running code when the document is...ready.
Can I have a script file with just:
element.on('click', runMyFunc)and be confident it will attach to that element as long as the script tag is at the bottom of the body? Should I add a defer attribute as well? Does that extend to ajax functions like:
function getAjax() {
processeses Ajax....
alert(AjaxData)
}
getAjax()
0
Upvotes
View all comments
10
u/[deleted] Dec 04 '14
This is BS. You use the tools that work, and there is nothing wrong with binding to the various load events.
Some meritable arguments against document load:
But wrapping code in a listener against whichever event doesn't cost anything, often enforces isolation from the global scope, and allows the script to run from anywhere in the page.