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.
Related
I was wondering if it's redundant to wrap code in:
window.addEventListener('load', () => {})
if you already have your scripts loaded at the bottom of the body tag?
Wouldn't that already ensure the DOM has loaded, making a load event listener unnecessary?
Correct. And, by placing the script at the end of the body, you actually reduce the complexity of the code and reduce the memory required to create and store an event handler. This is considered a best practice these days but it's not quite identical to setting up a load event handler. Instead, it's analogous to setting up a DOMContentLoaded event handler.
One caveat though is when you need to defer your code until all the external content referenced by your DOM elements has finished downloading (like pictures). Then setting up the load event handler is the way to go.
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.
First at all, I want know the difference between the $(document).ready and the $(window).load, then I know this.
But, I have some new questions.what is the ready event, what is the detail. what is the load event.
I have find the description of load event in the HTML spec.
But I can't find the description of the ready event.
ready() is an abstraction implemented by jQuery based on DOMContentLoaded.
load() (Note this jQuery method is depreciated) is based on window.onload.
The MDN articles link to the specification.
In JavaScript window is one of core object and defines several useful events e.g. onload, before jQuery comes, if want to execute any code, once DOM is loaded completely, we use window.onload event
There is a problem with window.onload , it not exactly executed when DOM is loaded but it executes after all content including big images are loaded completely. Browser normally delay executing onload code, until all page content is loaded, because of this user can see significant delay between they first see the page and the time that code inside onload get executed, this delay is particularly notable, if your page content heavy images, flash videos or other heavy content with low bandwidth internet connection.
jQuery solves this problem by introducing ready event, you might have seen code like below in several JavaScript files or HTML pages :
$(document).ready(function(){
alert("Inside jQuery ready method");
});
here $() is a shortcut for jQuery() function, and we wrap document object into jQuery object to use ready() method. We are passing an anonymous function to ready() method, which will be executed once DOM is loaded. It doesn't wait till all DOM content available e.g. images. By the way, instead of using $(document).ready() function, you can also use following short-cut, which has same effect :
$(function() {
alert("shortcut for document.ready method in jQuery");
});
Apart from faster execution, one of the key advantage of jQuery ready method over JavaScript window onload event is that, you can use them multiple times in your page, unlike onload event, which can only be bind to a single function. Browser will ensure to execute all document.ready code to execute in the order, they are specified in the HTML page.
Hope this will be useful for you.
Thanks
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 need to know in more detail of what is the differences between pageLoad , onload & $(document).ready()
I found answer but that is not ver clear to me.
the answer is like
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds funcionality to the elements in the page doesn't have to wait for all content to load.
the person trying to say ready event occurs after the HTML document has been loaded
and onload event occur after all page element like image etc being loaded.
So what is HTML document load? I know HTML document load means all page element load complete.
What does mean like dom is ready or loaded? What is the difference between HTML document load & dom load?
Please make me understand with example.
Thanks
I don't know what you mean by pageLoad, but here's some info on onload and $(document).ready().
window.onload fires when everything in the page has finished loading. That means that not only the entire DOM is loaded, but any linked resources such as images are fully loaded. Because this waits for images to finish loading, it can sometimes take a long time to fire window.onload. Unless you really need to wait until images are finished loading, you do not generally want to wait this long to start running your javascript that modifies the page or hooks up event handlers, etc...
$(document).ready() is a jQuery-specific event that fires as soon as the DOM is ready for manipulation, but potentially long before images have finished loading. This occurs after all objects present in the page HTML have been parsed and initialized by the browser and after all scripts in the page have been loaded. At the moment of this event, it is safe to modify the DOM in all browsers. This even may occur a little earlier or later in some browsers as the mechanism for detecting when the DOM is safely loaded varies between older and newer browsers.
The jQuery 1.6.x implementation for $(document).ready() uses a number of different detection mechanisms for when the DOM is ready. The preferred method is when the DOMContentLoaded event triggers on the document object. But, this event is only supported by some browsers so it has fallback mechanisms for other browsers.
Both of these events will fire only once per page.
Let's draw an analogy to compare the process of loading a web page to a chef with a recipe:
First, the chef (browser) reads the entire recipe (downloads the HTML document), to make sure that he understands the steps (HTML code) and that he knows what ingredients (images), utensils (style sheets), and appliances (external scripts) he will need to have in his kitchen (browser cache).
As the chef continues reading, he sends his assistant to the pantry to get the ingredients, utensils, and appliances (download the other files from the server). When he is finished reading the recipe ($(document).ready()), he starts to follow the steps (display the page), but sometimes he gets to a step before his assistant returns with the necessary materials to complete that step. He's pretty skilled, though, so he's still able to complete the later steps while he waits. (The analogy breaks down just a bit here, but basically: the browser lays out the page as well as it can based on the HTML; when you see a page load and then the fonts or layout change after a couple of seconds because it finally got the style sheet... just imagine that this chef is somehow able to add eggs to a cake that's already in the oven.)
It's only after the chef's assistant has brought everything identified in the recipe back to the kitchen (the browser has loaded all of the content) that the chef can put the completed meal onto the plate and garnish it (run the onload event code).
The onload event is a standard event in the DOM, while the ready event is specific to jQuery.
The DOM is the Document Object Model, a basic component of ordinary JavaScript. This means that all modern web browsers already know what onload means.
jQuery is a widely-used JavaScript library. In order for your script to properly use $(document).ready(), you will have to link to a copy of the jQuery library. Browsers don't know what $(document).ready() means without jQuery.