Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should event listeners be inside document.ready function or does it not matter?

Tags:

jquery

When I use:

$(document).ready(function(){

});

Should my event listeners (e.g $('button').click(function(){}) go inside that doc.ready function or outside according to convention?

like image 662
mohammad chughtai Avatar asked Jun 08 '17 21:06

mohammad chughtai


1 Answers

You should put anything in it that needs initialized AFTER the document object model is loaded. Including event listeners.

"Should my event listeners (e.g $('button').click(function(){}) go inside that doc.ready function or outside according to convention?"

HTML is interpreted from top to bottom so if your JS file is located in your head and you do not place it inside the .ready event then it will not be able to find your buttons since they haven't been generated yet.

If you put it inside your .ready event though, it is basically telling js to wait until the full dom object has been generated so the btn would then be found and bound.

On the other hand, there are people who strongly believe in including their js files at the very bottom of the page. Since HTML is interpreted from top to bottom then the js file will be loaded after the "meat" of the dom has been generated and you would not need to encapsulate your event binding inside .ready

like image 175
Travis Acton Avatar answered Sep 28 '22 05:09

Travis Acton