I have a page with <form> tag. Inside a form there is a lot of html plus some inline JavaScript at the very end of the <form> tag.
I listen to document load event. Can I be 100% sure, that when document load will be fired, all this inline JavaScript code has been already executed?
Example of markup:
<body>
<form>
--html controls---
<script type="text/javascript">
--some code to run here--
</script>
</form>
</body>
My thoughts that answer is yes, inline JavaScript will be executed before document load, but I want to find evidence.
edit
live demo
Document load fires only when all html controls loaded and JavaScript (inline or with src attribute)loaded and interpreted. Am I correct with this statement?
Unless you put the code you want to execute in the domready callback function, your inline javascript code will be executed immediately when you load the page (before the the domready).
Inline script will execute immediately as soon as the script tag finishes parsing, so you won't be able to access the rest of the document yet. On the other hand, it allows you to write additional HTML at that point in the document.
Note that Firefox 3.5 had a bug whereby you could set the defer attribute on the inline script and it would not execute immediately. This non-standard behaviour was fixed in Firefox 3.6.
I think you have no guarantees
If it is a slow javascript (emscripten) i think it is possible that the code is still beeing executed while the onload fires.
but i could not find clear documentation:
https://developer.mozilla.org/en/DOM/window.onload
http://msdn.microsoft.com/en-us/library/ie/cc197055%28v=vs.85%29.aspx
http://www.w3.org/TR/html4/html40.txt :
onload = script [CT]
The onload event occurs when the user agent finishes loading a
window or all frames within a FRAMESET. This attribute may be
used with BODY and FRAMESET elements.
so I can't find guarantees, you can either test (with something heavy, e.g. a demo from here https://github.com/kripken/emscripten/wiki), hpe for the best, or build in a savequard of your on that checks weather your inline script completed
Related
This question already has answers here:
document.ready inside body tag
(2 answers)
Closed 9 years ago.
We often read here and there, that we must place our js code either on the page head section or before (sorry) the end body tag. Discussions about this aside, I'm just looking to know what are the reading order for such things by the browsers (taking that they do act as equals here):
Can we place:
$(document).ready(function(){
No matter where on the page structure, because we are using $(document).ready or should we still place it on the head section ?
Can anyone please clarify this.
If my question isn't clear, I can rephrase.
You can place a script anywhere in the document. Best practice usually advises placing scripts in the footer for page load performance concerns. Further, best practice usually advises placing the scripts together for ease of maintenance.
However, per the spec, there is no restriction on where in the document you place a script tag. You may place them together in the header, at the bottom of the body, sprinkled all over the document, or any combination thereof.
The use of the jQuery construct $(document).ready has the same result regardless of where it is placed within the document. The key is to understand the functionality behind this construct:
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received.
So, ready is similar to document.onload, but not the same. It doesn't matter where the code is, if you execute it when document.onload is fired or when jQuery fires ready. Code's placement in a document is only significant if it is NOT wrapped by some event handler/listener.
The only restriction on the location on $(document).ready is that it cannot happen before you include the jQuery library. $(document).ready is using jQuery, so if jQuery doesn't exist.... you can't use it.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
alert('executed as soon as it is reached (as the document is downloaded)');
$(document).ready(function () { alert('on jQuery ready'); });
</script>
</head>
<body onload="alert('executed on document.onload event');">
<script>
alert('executed as soon as it is reached (as the document is downloaded)');
$(document).ready(function () { alert('on jQuery ready'); });
</script>
</body>
</html>
Documentation
SCRIPT specification at W3 - http://www.w3.org/TR/html401/interact/scripts.html
script (html 5) specification at W3 - http://www.w3.org/TR/html-markup/script.html
Placing Javascript in your pages at quirksmode - http://www.quirksmode.org/js/placejs.html
Jquery ready - http://api.jquery.com/ready/
AFAIK, $(document).ready event gets raised after DOM is completely loaded so it doesn't matter where you place it.
But they say to write the script at end of the body because page will show up to the end user instantly and javascript will continue to run as background process.
The browser executes the script from the top to the bottom, so the srcipt in the head section will execute before the script in the body. I prefer to put the script undernith the html code, but generally it desn't matter much if you vait for the page to fuly load.
The document ready function will wait until the DOM is loaded before running. So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded. Other people like putting it at the very end (just before the end body tag) so that all of the elements of the page are loaded before the script reads them. But since you're waiting for the DOM to load anyway, it doesn't matter.
If you have a small function, then I would just put the document ready function in the head tags.
As far as i know, the BKM is to place it in the footer (although mostly developers tend to place it in the head tag).
Main reason - most of the document DOM is rendered to the browser prior to loading JS.
I lately saw some sites which uses this pattern :
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function (){...do some stuff with plugins...});
</script>
</head>
<body>
<script src="myplugin1.js"></script>
<script src="myplugin2.js"></script>
<script src="myplugin3.js"></script>
</body>
</html>
This made me think of some traps :
Question #1
document.ready event is raised not executed after the plugins(JS) has been parsed.
it is executed when the dom structure is done. (notice: I didn't say :"when all resources has been downloaded" !)
So there could be a situation where the document. readyfunction will try to use a plugin variable which hasn't been fully downloaded. (which will cause error).
Am I right ?
Question #2
This leads me to : "never use document.ready" before the script references location ( I mean : in situations where document.ready is dependent on those script variables).
Am I right ?
p.s. Im not talking about window.load which will obviously will work here but i'll have to wait much longer.
If you think about all the kinds of resources in a page, many can be loaded separately from the page content: images and stylesheets, for example. They may change the look of the page, but they can't really change the structure, so it's safe to load them separately.
Scripts, on the other hand, have this little thing called document.write that can throw a wrench into the works. If I have some HTML like this:
Who would <script>document.write("<em>");</script>ever</em> write like this?
Then browsers will parse it just fine; document.write, if used at the top level like that, effectively inserts HTML at that position to be parsed. That means that the whole rest of the page depends upon a script element, so the browser can't really move on with the document until that script has loaded.
Because scripts can potentially modify the HTML and change the structure, the browser can't wait to load them later: it has to load them at that moment, and it can't say the DOM is ready yet because a script might modify it. Therefore, the browser must delay the DOM ready event until all the scripts have run. This makes it safe for you to put the dependent code at the top in a ready handler.
However, I'd recommend you don't, because it's not very clear.
The event that $(document).ready equates to is DOMContentLoaded in modern browsers (and it falls back to some others in legacy browsers that equate to the same scenario).
MDN summarizes it pretty nicely:
The DOMContentLoaded event is fired when the document has been
completely loaded and parsed, without waiting for stylesheets, images,
and subframes to finish loading (the load event can be used to detect
a fully-loaded page).
So your scripts will always be parsed by the time it is executed.
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 normally work with jQuery as it's convenient to use the document ready feature so I can wait until the DOM is ready before attaching event listeners to DOM elements.
I've inherited a project that, at least for a while, is going to be using a lot of inline event calls:
<element onclick="doThis()">
Not pretty, but what I have to work with.
Normally I'd load the JS file at the bottom of the HTML page. However, if I do that in this case, does the event wait until the document is ready (body load) to try an execute, or will that onclick event fire as soon as the element is clicked regardless of whether or not that big JS file has loaded yet?
I think the latter happens, meaning that in this situation, I can't be moving my JS file out of the HEAD for now. But wanted to confirm.
An event handling attribute on an HTML element is like a mini script block which is evaluated independently of other script blocks on the page. In the case of onclick="", as soon as the element is read into the DOM, the event handler attribute has been evaluated and will attempt to run if the element is clicked.
You can think of those attributes, by the way, as functions. The code between the double quotes of the attribute definition is the same as the code between the curly braces of a function definition.
onclick="/* IN HERE */"
is the same as
elem.onclick= function(){/* IN HERE */};
The function is defined upon being evaluated by the browser, and executed upon click.
If anything provides for the code in the /* IN HERE */ area and has not been loaded into the DOM by the time the element makes it into the DOM, clicking will cause an error.
As I said, all script blocks and inline handlers are evaluated separately. So your scenario of clicking is the same as follows:
<!-- same as firing the click event -->
<script type="text/javascript">
doSomething();
</script>
<!-- externally loaded script file--late! -->
<script type="text/javascript" src="/path/to/provides_doSomething.js"></script>
yep. when you click, the onclick event will fire even while your javascript scripts is loading. it will append the function call to the queue and when your script isn't loaded yet, it would result to an error.
so maybe you can add bit in your code to check if its loaded:
<element onclick="if (doThis) {doThis();}">
The user won't be able to click the element before the DOM is ready.
What's the difference between executing a JavaScript function on jQuery's $(document).ready() and including it in the HTML in script tags at the end of the body?
Thanks,
DLiKS
JavaScript code inside the <script> tags is evaluated (executed) immediately. Note that in this case the page has not been parsed yet (entirely), and the DOM is not yet ready.
JavaScript code inside the jQuery ready() callback is evaluated on the DOMContentLoaded event, which occurs after the entire HTML source code has been parsed by the browser.
About this event: https://developer.mozilla.org/en/Gecko-Specific_DOM_Events
Note that the modern way of defining the ready handler is this:
$(function() {
// code
});
Also, check out this SO question, which points out what happens when you don't use the ready callback: How many JavaScript programs are executed for a single web-page in the browser?
A script at the end of the body will
run as soon as it is loaded.
$.ready is executed after the document is complete (any
linked css is also loaded).
Body.load runs
only when all images are loaded as
well.
This SO question might be helpful.
If you call a function in a script that is placed next to the closing body tag (</body>) it's the same thing as using $(document).ready(function(){}); in the <head> section.