The right place for running a jQuery - javascript

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(){ ... ?

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

$ is an alias for jQuery, so you can pick what ever you prefer and stick to it. There are some advantages of using $. It is slightly more compact and commonly used in the jQuery documentation.
In your examples your anonymous function was called when document was ready. One thing that is good to know is that images might not be loaded when using document ready. You can be sure that are DOM elements are there, so your jQuery selectors should work correctly.
If you have multiple $(document).ready(function () { /* your code here */ }); lines then all them are executed, so they don't override each other. For example if you multiple JS files. You should separate your JS files for maintainability.

Related

How important it is to wrap jquery code in $(document).ready() function?

I have been developing my frontend code with jQuery for a while now, and since I am implementing the site with partials in rails. Often I would use content_for :javascript to wrap up some code that is specific for a view.
and my question is, I end up with a lot of script tags and since most of them are jquery code, I have typed up a lot of $(document).ready(function() {});
So my question is, whether it is necessary to wrap everything in document.ready, and if I have too many of document.ready will it affect the performance?
$(document).ready() has one purpose - to execute some code after the DOM has finished loading and is now ready for access or modification.
If your code is located before DOM elements such as in the <head> tag or in the top or middle of the <body> section before some DOM elements and that code does attempt to access the DOM upon first initialization, then it should be placed into a $(document).ready() block so it will not execute before the DOM is ready or the ` tag should be moved.
If your code is in a <script> tag within the <body> that is after the DOM elements that it needs to access then your code does not need to be in a $(document).ready() block.
Or, if your code is not called upon initialization (e.g. it's only called later upon other events) or your code does not access the DOM upon initialization, then that code does not need to be inside a $(document).ready() block.
Though you obviously have jQuery available, you can read this answer for a more detailed description: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it.
Having multiple $(document).ready() blocks is just like registering multiple callbacks for an event. It's really no big deal. Each one just takes an extra couple function calls to setup and is an extra callback execution at execution time. If that's the cleanest way to write your code, then by all means use multiple $(document).ready() blocks.
To summarize, put code into a $(document).ready() block when:
A specific block of code needs to access the DOM when it is first run and the code is located in a script tag that is placed before the end of the <body> tag or is placed before some DOM elements that it might need to access.
There is no need to put code into a $(document).ready() block when:
The part of the code that runs at first initialization does not access the DOM.
The code is placed into a <script> tag that is after the DOM elements that it references.
The <script> tag is marked defer because this explicitly instructs the browser to delay the running of this script tag until after the DOM has been parsed.
Also, keep in mind that it does not matter where functions are declared. It only matters where the functions are called from. So, you can define as many functions as you want outside of $(document).ready(). You just have to make sure that any functions that access the DOM are not called too soon.
If your code does access your DOM element but you put it outside $(document).ready(), it may subject to fail or produce unexpected behavior. See this example below:
var listA = $('ul.myclass').children();
$(document).ready(function(){
var listB = $('ul.myclass').children();
});
From simple snippet above, listA is calculated straightaway when the script is loaded even your document has not been fully loaded or ready, while listB is calculated when the document is loaded and ready.
listA and listB could be different in this scenario even though they are calculated from the same DOM selector.
It's OK for you to initialize some variable values or pre-load some values which have nothing to do with the UI outside of document.ready(). But when you want to initialize your UI or access the DOM upon startup, always do it when the document finishes loading (document.ready).
I agree with everything #jfriend00 says but also remember that not all your code needs to be in the document.ready event. What I mean by that is that you can create your functions at any time, they only need to be executed at document.ready. For instance:
function manipulateDOM( el ) {
document.getElementById(el).classList.add('myClass');
}
$(document).ready(function()){
manipulateDOM('myEl');
});

Succinctly Adding Custom Event Triggers in jQuery

I have a rather large and convoluted JavaScript module that is used on multiple pages of my site. After a bit of searching and fiddling, I came up with the following structure to run some extra code when one of the module's functions run on a specific page.
// within module definition that is used across multiple pages
function some_module_method(){
$.event.trigger( 'custom_event' );
}
// bit of functionality that I'm trying to add to a single page
$( '#some-element' ).on( 'custom_event', function(){
console.log( 'The custom event has just been triggered!' );
} );
One problem I'm having is that when I'm expecting this event to only trigger once, it will go off 2-4 times in quick succession. Is this a problem with the structure above that I'm using to trigger and attach this event, or probably something else?
Also, how can I attach a function to an event without referencing some DOM object? Simply using $.on() doesn't work.
For your first issue, it's a little hard to say without seeing an example. And I could be mistaken, but I'm pretty sure $.trigger() will not work like you're using it. It has to be attached to a jQuery object e.g.. $().trigger().
And for your second question... You don't have to use a DOM element exactly, but you can use an empty jquery object like $({}).on(). See this fiddle.
Hope this helps some.
On a side note, you may be confusing jQuery object methods with core methods. here is a little info just in case.
Use
$('#some-element').trigger('custom_event');
instead of
$.trigger('custom_event');

jQuery ready, is it always needed?

Regarding my question here: Validate dynamically added control
Should we always use the ready function on javascripts?
One should only manipulate the DOM when it is guaranteed that such an operation is valid and behaves in a well-defined manner.
Delaying execution until the "document ready event" (jQuery.ready) ensures the DOM is "complete". However, depending upon browser and context, it is quite possible it is not needed -- not something I like to bet on (it also involves more thinking and makes code more dependent upon the HTML/code order).
Happy coding.
JQuery documentation shows this below:
All three of the following syntaxes
are equivalent:
• $(document).ready(handler)
• $().ready(handler) (this is not
recommended)
• $(handler)
Any JQuery starting with $(handler) executes when the DOM is ready. You don't need to worry about the ready bit.
SOURCE: http://api.jquery.com/ready/
No: it is only needed if you need to wait for the DOM to finish loading.
You can also use the "live" function to bind which may decrease page load times as described here
http://encosia.com/2010/08/18/dont-let-jquerys-document-ready-slow-you-down/
Read this
The .ready() method is generally
incompatible with the
attribute. If load must be used,
either do not use .ready() or use
jQuery's .load() method to attach load
event handlers to the window or to
more specific items, like images.
U can Google or search on SO for similar answer
You do not need to use document ready. place your jQuery just before </body> tag and your other jQuery scripts and plugins after your jQuery as such.
<script src="jquery.js"></script>
<script src="other.js"></script>
<script>
$('div').click.....
</script>
</body>
There's a great article about this "don't let document ready slow you down"
Depends the element your workin on, you have many possibilities.
If it's juste for a navigationbar or a module you can chose different DOM elements.
/* for a menu */
$('.menu').ready(function() {...})
/* for the all page */
$(docuement).ready(function() {...})
But you can also include your jquery file and your script at the end of page.
<script src="jquery.js"></script>
<script>
$('.menu').click(function() {...})
</script>

Necessity of .ready() in jQuery

I've seen various examples use this and I'm curious to know, is it dangerous not to wrap jQuery code in the following?
$(document).ready(function () {});
I know what it does and I know why you do it but I'm curious if it is more unsafe or just bad practice/style to not have it? Thanks!
You use it if your code needs to access the DOM.
If you're just setting up classes and modules, but not actually running them, then you don't need to wrap them in the ready handler.
However, if you're doing something that requires elements to be loaded (like, adding event handlers) then you need to do it in the ready() event.
EDIT:
Here is an example: http://jsfiddle.net/ctrlfrk/43n8U/
Try commenting out the addHandler functions and see what happens.
(Note that I've set jsfiddle to run this code in the head tag, by default it usually places the code in the onload event, which negates the need for the ready handler)
It depends on where you are placing your scripts. If you add a script tag just before the closing <body> you don't need to use it because the DOM will already be loaded. On the other hand if you place your script tag inside the <head> section and access the DOM you absolutely need to use it or your script won't work because at the moment your script executes the browser hasn't yet read and parsed the DOM.
See this (already answered)
jQuery ready function aliases
for those that the above is tl;dr; :
Additional reading: http://api.jquery.com/ready/
Wrapping your code in ready() function only delays the running of that code until the page has been loaded. The code does not get "safer" somehow.
But many times you want to run some code that will query the DOM that is created after the script-tag that your code is in, or simply need some structures from the document that are placed after that script tag. If that is the case, then ready() is for you.
But generally there is no valid reason not to use ready() function, so that's why everybode almost always use it.
I think you should also be aware of jQuery's $(window).load() and how it differs from $(document).ready()
Read more about it here

Simple questions about ajax - Help me understand

I need a little help understanding something. I am using the colorbox plugin to load an external an external html snippet (which works fine). But none of my jquery selectors see the newly loaded html. Is that right (I think it is)? and if so how do I work around that.
Thanks
When you set any properties/bind events in your $(document).ready(function() { ... }) they are executed on page load. So it is all applied to the DOM elements that are present initially.
But when you call the AJAX request and insert some elements into your document, the jquery statements are not executed again (because document.ready doesn't fire). Some solutions to overcome this are:
execute the inside of the document.ready function or the relevant part of it after you insert the new elements.
if the only thing you need are event handlers that should be bound the the new elements you may use live events.

Categories

Resources