I'm currently learning jQuery after finishing JavaScript course. The document says that the ready method waits until DOM finished loading. However, I have 2 points I'm curious about.
1) Since the script tag are usually added at the end of the body tag, shouldn't the DOM already finished loading anyway without the ready method.
2) If we need the ready method in jQuery, why do we not need it when writing usual JavaScript too?
1) Since the script tag are usually added at the end of the body tag, shouldn't the DOM already finished loading anyway without the ready method.
Yes you are right, if script tag is added add the end of the body, you do not need to wrap your code with $(document).ready() as the DOM elements are already available to use in the code.
2) If we need the ready method in jQuery, why do we not need it when writing usual JavaScript too?
The jQuery equivalent of $(document).ready() is DOMContentLoaded
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
Please Note: You can also use script defer attribute
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.
Related
What is the difference between placing a script at the end of tag vs adding it on the head and using document on load to assure the html content is already rendered. Placing it at the end of the body wouldnt already assure the content is loaded and ready to manipulate?
Using the 'onload' event provided by the browser has always worked for me. It has the upside that moving the script tag doesn't break your code.
The load event only fires when all images and potentially other resources like style sheets have loaded. This is not yet guaranteed when the script, that is placed at the end of the document body, gets executed. Often that is also not needed for the script to execute correctly, as it can access the DOM.
See also on MDN:
load event
DOMContentLoaded event
I have a somewhat large .js file that is currently called in the header of a HTML page, but it fails to execute because the elements have not loaded when the script is called. What is the best way to implement this? I've tried adding
document.addEventListener("DOMContentLoaded", load, false);
to the script but that doesn't seem to work. Calling the script in the footer or inline is not an option, nor is JQuery.
Meet onload.
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
There are also Gecko-Specific DOM Events like DOMContentLoaded and
DOMFrameContentLoaded (which can be handled using
EventTarget.addEventListener()) which are fired after the DOM for the
page has been constructed, but do not wait for other resources to
finish loading.
A question/clarification regarding Javascript/jQuery execution and it's sequence.
Please excuse me if I seem to answer my own question here, but I feel I'm missing a key something in this process.
I was told my selectors weren't taking because the DOM wasn't ready which had brought this question. Script was initially in the head using the ready jQuery ready method.
Thanks everyone.
Problem:
No access to Drupal template files.
Can only add in the head.
Appending via jQuery isn't too useful with the script tag.
Our solution currently is linking to the file in the markup.
I'm really seeking clarification though to the process here.
Context:
(Sorry bout that)...
Element wasn't targeted by my selector, from the script in the head. Syntax was correct, as it targeted the HTML tag without issue.
My understanding was the ready method/resulting listener would trigger after the DOM was fully constructed.
What I believe I already know:
I know scripts should ideally be placed just above the closing body tag in the markup.
I know that when the tokenizer encounters a script tag, it stops everything and executes the script (unless defer/async).
I know this is why they should ideally be placed above the closing body tag so the DOM is ready.
I know that the jQuery ready method attaches a listener, when the browser is switched to it's ready state after the DOM has been loaded, it fires.
The Questions:
Given all of this, placement in the head renders the ready method useless as its being executed right away because of the tokenizer?
Is this really just to avoid colliding/overwriting multiple window.onloads? (Should've clarified.)
Given all of this, placement in the head renders the ready method useless as its being executed right away because of the tokenizer?
Wrong. The ready() method gets called only when the DOM has fully loaded, all ready() does is that it establishes a listener that waits for the DOM to load so that statements inside the ready() method get executed when the DOM is ready to be manipulated, in other words it adds a listener to the loaded event that gets called and executed only when the document has full loaded.
Is this really just to avoid colliding/overwriting multiple onloads?
What do you really mean by "colliding/overwriting" ? You can have several listeners listening to the same events in JavaScript, and they won't overwrite or collide with each other.
From your question:
I know that the jQuery ready method waits until the browser is switched to it's ready state after the DOM has been loaded.
Well, sort of. The jQuery ready method doesn't wait. It attaches an event listener. The function is attached, but not executed. The function is only executed when the DOM is ready; the rest of the page continues loading.
You're really in the sphere of micro-optimisation here. Yes, placing script elements at the end of the body is ideal, but it will make minimal difference in reality, unless you have a huge, complex and time-consuming script.
If we call a javascript method myMethod() in a script tag which is before closing body, is it equivalent to calling myMethod() inside jQuery's document.ready function ? If not, Why ?
From here:
Under the hood: $(document).ready() As you would expect from John
Resig, jQuery’s method for determining when the DOM is ready uses an
assortment of optimizations. For example, if a browser supports the
DOMContentLoaded event (as many non-IE browsers do), then it will fire
on that event. However, IE can’t safely fire until the document’s
readyState reaches “complete”, which is typically later. If none of
those optimizations are available, window.onload will trigger the
event.
These events are independent of a location within the HTML tag, as other event still are going on even at the time of rendering </body>.
No it's not the same, you place the <script> tags before the closing </body> tag to avoid blocking the rendering of html on older browsers, AFAIK, but you have no guarantee that the DOM is "ready"
Not exactly. $(document).ready(); reacts on the so called DOMContentLoaded event which is fired right after the DOM has been loaded and the browser is aware of all the elements on the page (not the content itself).
The main reason why code is usually put inside these blocks is not that much related to preventing blocking of parallel loading but to ensure that the elements which are to be manipulated during page load are actually loaded and present in the DOM tree. Not much sense in manipulating elements which the browser is not aware of right?
Putting JavaScript content (or any other content for that matter) at the bottom of the page is actually more closely related to the onload event which is fired after the page has finished loading, including the content itself. Either way its almost certain that content inside $(document).ready() blocks will be executed before the one at the bottom of the page however if you load external libraries on which the code inside the ready() block relies you can't put those at the bottom of the page.
In general if you have code that isn't dependent on external libraries and a successful loading of DOM you can safely put it at the bottom of the page. If you however have stuff that needs to be executed right after the DOM has been loaded you most definitely want that code in the $(document).ready() block, but do have in mind that you can place that block wherever you want, even in the middle of the page (which can be a nice trick sometimes).
I have written an external script that needs to run after DOM is ready (or after onload if thats impossible).
I use this method to load the script dynamically since I need parameters on the script:
<script type="text/javascript">
document.write(unescape("%3Cscript src='mydomain.com/script.js.php?u="+encodeURIComponent(window.location.host)+"' type='text/javascript'%3E%3C/script%3E"));
</script>
To start the script on time I use cross browser methods to attach the dom ready or onload events.
My question: Can I assume that DOM is ready when my script runs and run my script immediately or that DOM is not ready, and attach to DOM ready event (OR document load)?
If I cannot assume for sure either, my question is how can I tell if DOM is already ready (on the different browsers) when my script runs? In this case the methods to start the script on DOM ready or document load events will not work because the events were already fired.
Notes: 1.I have no control on the web sites the script will be attached to.
2. Can't use Jquery or other library.
You can be almost sure that dom is not ready yet.
This is a good reference to get this working as you want.
I would either:
1) Load dynamically that script and then attach function to onload even to call/do whatever you want with that off-site .js .
2) Load the script only after DOM is ready.
Put the script near the end of the body of the document. Anything above will be available when your script is invoked (because the browser will have to have parsed it to see your script tag; QED).
Note that other resources (like images or frames) can still be loading at that time.