February 27, 2012

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 and clicks

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!