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>
Related
I'm using an external JavaScript file to access DOM objects with in my documents. The problem is that jQuery doesn't seem to have access if it's an externally loaded file. My code looks like:
<html>
<head>
</head>
<body>
<div id="domToChange" someAttribute="hi"></div>
<script src="officialJqueryLibrary"></script>
<script src="myJS.js"></script>
</body>
</html>
///////// myJS.js file
// Returns undefined
$('#domToChange').attr('someAttribute');
The DOM selector doesn't seem to find my div when the JavaScript file is loaded externally. However everything works when I place it inside the HTML document itself. How can I give DOM access to my JavaScript file?
You should wrap all your DOM related code into
$(function() {
//Code
});
Then the code gets executed when the DOM is fully loaded.
Try getting the value for your attribute, like so:
$('#domToChange').attr('someattribute');
//or
$('#domToChange').attr('someAttribute'); // i know you've tried this, but pls check demo
Demo here. On my machine, browser Chrome Version 28.0.1500.95 m, it just works fine.
OK, this is a hit and miss kind of thing (but I believe it be an accurate explanation), but the real explanation for why it is happening lies here.
You need to understand that jQuery is an object that is initialized. So the jQuery object takes time to initiatize. As it says,
is very important to make the distinction between jQuery object and native DOM elements. Native DOM methods and properties are not present on the jQuery object, and vice versa.
So it is not necessary that the jQuery object gets initialized at the same time the DOM gets initialized.
Also, all scripts that are passed have a defer attribute. This is mostly browser dependent.
As it says,
When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering.
And it can sometimes delay the execution of the script. Hence the different result according to different people.
You have to enclose the code like this:
$(function(){
$('#domToChange').attr('someAttribute');
});
So that the code is executed when the DOM is ready.
This is most likely already a question somewhere, but I cannot find it, as EVERY single search turns up jQuery questions.
I'm looking for a proven method to bind to the document being ready, much like jQuery's $(document).ready(). However, this is for a "modern browser only" page, with very light javascript, and I'd like to avoid loading jQuery here.
Would someone kindly point me in the right direction?
Thanks!
document.addEventListener('DOMContentLoaded', function () {
/* ... */
});
The event "DOMContentLoaded" will be fired when the document has been parsed completely, that is without stylesheets* and additional images. If you need to wait for images and stylesheets, use "load" instead.
* only if the <script> is before the <link rel="stylesheet" ...>
window.onload = function() {} is a standard from the long past ago, whereas it also waits for all the images to load, it is basically a working, functional alternative for some such cases also in all old browsers. A user usually still should wait a second till he makes a responsible action.
Edit: In my case, I needed it for all the libraries being loaded prior to anything else, as they were listed fixed in the footer (jquery). At it is mine dependency to continue to work with is possible just once it is loaded. So IMHO the fact that the user has to wait is irrelevant (unless I miss something here and am available to be explained), as it's the case with any way of jQuery loading, till it's not loaded it can't be worked with it. For the sake of that point ofc any way there must be a backend check as client-side js can be "intercepted". Waiting for an entire document to load is certainly more lengthy than using it just after its inclusion, however this is for cases when you eg. can't affect the order of html scripts, eg when you use it in own 3rd party package.
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.
Is it really necessary to wait for the "ready" (or "window.onload") events if your code only manipulates DOM elements that have already been parsed entirely?
The jQuery documentation for the "ready()" function demonstrates how you could wait to perform actions until the DOM is entirely ready but the example is for code (script tags) that are listed before the DOM elements in question. But it seems that code which appears after the necessary DOM elements in an HTML document has access to them since, presumably, the DOM is built as the browser parses the document.
For example, is it safe to assume that the following code is reliable in all situations or is it still necessary (or beneficial somehow) to use a ready/onload handler?
<body>
<div id="foo"/>
<script type="text/javascript">
var foo = document.getElementById('foo');
foo.innerHTML = 'The element #foo is loaded!';
</script>
</body>
This SO question is very similar but I wanted to bump it to see if there is any more information.
If your JavaScript code is below the DOM elements and only modifies them exclusively, you don't need to wait for the DOM ready event.
However, keep in mind editing a DOM element which contains a script element (or more specifically, before the element's closing tag) used to cause big problems in IE6 (thanks T.J. Crowder) and IE7.
However, this requires inline scripts which can be a maintenance problem. It is preferred to have your JavaScript stored externally (and many speak of the benefits of including them before the closing body tag) for many benefits such as ease of maintenance and fine grained cache control.
in your case it is fine because the browser will render your code line by line and in your code id="foo" comes first so it will get that div....but suppose you wrote this script in head tag then the script will run first and it wont get the div with id="foo" because its not yet loaded..its better to write in document.ready method
Yes, it's safe if you js code is after dom but usually it's not relly good idea to mix html and js.
Document is loaded in linear fashion so your code works correctly.
Sometimes programmers do not use document ready for performance purpose when the javascript is not depends on the DOM below it. Here is some example.
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