The right place for running a jQuery
Question by Constantin.FF
Adding different plugins, scripts and other jquery the code gets pretty messy.
What is the right place for running each jquery, and does it need separated functions for each element.
Some of the scripts are runs like this in the head of the page:
$(function(){ ...
jQuery(function() { ...
and other need to be at the end:
$( ".add" ).button({ ...
is it wrong to merge all of the functions into one $(function(){ ...
?
Answer by Starx
There is NO hard-n-fast rule for where to put a jQuery
snippet.
You put it at correct place where it is needed.
-
$(function(){
is short for$(document).ready(function() {
. It is an event, which executes when the document is ready for processing. -
$( ".add" ).button({
is assigning a plugin(probably) to an selector. Every plugins have their own event triggers and they will occur either automatically or manually like through,hovers
andclicks
You should put(always) code at the correct event triggers/function call for them to function properly.
But
If you are using too many scripts on your page, that it is slowing the load time. Then they are better when they are placed right before the </body>
References
Read jQuery Events Documentation [docs here] very clearly to understand, where to put your code effectively