Do you know if it is possible to make sure that a JavaScript script site is ran first in a web page?
For the context, I'm trying to tag every span before another library (just like cufon) kicks in and messes with the original content. Since it's not possible to use onLoad() on spans, it's the only way I can see to do that on the client side.
Order of precedence is determined by the order in which things load.
Head tag scripts (in the order they are listed)
Scripts & other event attributes in the order they appear in the code.
Body onLoad
I did have #2 & #3 mixed up - to clarify the body onLoad event fires after the entire body (scripts included) loads
Also, scripts altering <span> tags will have no effect if placed in the head tag (unless they are a function) since the script runs when it is loaded, and when the head loads, the body & span tags haven't loaded yet.
Place <script> tag in page source after content that you need to modify, but before any other scripts. Scripts run in same order that their tags appear on page.
Related
I have read a StackOverflow answer here, as it says:
Also, place the <script> tags at the bottom of the page, even after
</body>, but before </html>. This will load the scripts last and load
the ads last.
Is it real? Why it would work?
Loading a "classic" script is synchronous by default. This means that when the script tag is encountered, the HTML parser will wait for this script to be downloaded and executed before it is able to continue parsing what follows.
So, yes, putting your script at the end of the markup will allow the parser to have gathered enough DOM information and stylesheets and everything before it gets blocked fetching that script.
The renderer may even be able to pre-render the page while this script is being fetched, making it looks like the page did load faster.
But no, placing it after the tag won't make anything "speed up" in comparison to placing it before. This will just create an error in the parser, which will have to move it back inside the <body>, and it will make your page fail to pass validators. (Though to be fair, this was not the claim made in that quote).
Also, note that just doing this that way will still block the parser synchronously, and thus, all the asynchronous tasks that should happen at the end of the parsing will still get delayed.
So the best if you want to load a script that doesn't need to execute synchronously is to load it with the async attribute.
The purpose of adding at bottom of the page is, controlling the compile-time errors.
Consider the scenario, we have written some addClass() functionality to an ID element, if we include this in top it can't find out the Id element.
So we are adding it to the bottom of the page, once the DOM has been loaded.
TL:DR; faster? No, not really. The impression of loading faster? Yes.
When the browser is rendering the DOM and it comes across a <script> tag, it must halt, execute the JavaScript, then continue. This is because the JS could be doing anything, like appending another element, where the order is necessary. If it queued the script for loading later or made it async, by the time the script finished executing the state of the DOM might not have been the same when the script first started loading.
E.g, consider the following:
<p>Hello</p>
<script>document.body.innerHTML+="Wor"</script>
<p>ld!</p>
In this case, the order of the tags is necessary. If the browser queued the script to be loaded later, the last paragraph tag may have been rendered before the script inserted Wor into the body innerHTML, and you would end up with:
Hello
ld!
Wor`
But what if your script is doing some intense work that could lag out the browser for a few seconds? If you put the script tag in the middle of the body, half the page would be rendered, the script would be run, then the other half would be rendered (after script execution finishes). This gives the impression that the first half loads immediately, but the second half took a few seconds to load.
This causes a bad user experience. Instead, what's recommended is to move the script tag to the bottom, so only once the browser has finished rendering the elements should the script be run. This isn't faster, it just gives the impression of being faster.
I have read in the docs of some third party providers (e.g. adsense) that their script must go in the <head>.
For async scripts I'm fairly sure this is untrue since the async flag doesn't guarantee anything about when the script will be executed. But I'm curious about non-async scripts too. Does it makes sense to say that a script tag must go in the <head>?
(This is assuming that there isn't any code in the page that relies upon some script having loaded).
To be clear, my question isn't "is it a good idea", or "what are the performance benefits".
It's more like: "is it technically possible that a script could NOT work, because it isn't in the <head>?"
Thanks!
A <script></script> in the <head> tag will stop the DOM from parsing until the script has loaded. Put scripts here that need to be loaded before the DOM is parsed. Don't put any unnecessary scripts here, as it stops the DOM from parsing. That results in a slow-to-load page.
See: https://stackoverflow.com/a/24070373/47589
The MDN page on the script tag does not place any requirements on the location of a script tag. In fact it seems that the modern trend is now to put scripts at the very end of the body.
A tag can be placed anywhere in the html page, But placing in the tag will slow down the creation of DOM elements in the browser, because browser needs to get all the script tags and move to html elements,
The best practice is to keep the script tag at the bottom of DOM elements, because the visual html elements will be loaded before the script js getting load.
It mainly depends on the functionality of the script and the business logic of the page.
I'm stumped with a very simple question. Since the <body> tag always precedes content, when does body onload execute; at the opening tag or at the closing tag? Can body onload advance to a point where it ignores code inside of it?
And so then maybe I skipped this part at the very basics of coding... If I open a tag with say, a style property, and don't close it, will it still execute?
Body itself is the content of your page, no pre-loading as such..
So if you run an onload event, this will trigger once the content of your body is ready and generally has rendered itself or is about to.
In general, you would create any content within the body tag or using a script at run time and then run a onload script to finalise everything.. This could be use to add javascript hover effects or to hide a progress bar for loading.. Generally once that script is done. The page should be ready for the user.
Code will never be ignored ever (with exception to crashes/cancelled requests), But it depends if the code is taking effect like it should.. You element might not be ready if your adding it dynamically..
Another big issue to watch out for while developing is cache, this is a nasty creature that will waste hours of your time...And last but not least, use the browser console to debug at various points and test what is happening.
As for closing tags, If you mean you you do not put the > character at the end, it will break the page.. In the case of tag like link.. But for a script, you must close it upto the point of the < /script > tag
$(function(){}) is the the same as jquery's $(document).ready so I am wondering if I can put it into body
instead of head ?
I only see the act of putting script at different section of the page as a matter of executing it at different time. It is true? Can I put script in a div in the middle of the page? Will it affect how DOM is loaded?
I only see the act of putting script at different section of the page as a matter of executing it at different time. It is true?
Yes, but the script you're talking about just makes a single function call (to ready). The callback will get called later, when the DOM is ready, either way.
Can I put script in a div in the middle of the page?
Yes. But again, if the script in question is just calling ready (directly, or via the shortcut), it doesn't much matter. I would discourage you from littering scripts all over your markup; best to try to keep the two largely separate.
Will it affect how DOM is loaded?
Only if you use document.write within the script (and even then, it doesn't affect how the DOM is loaded, but may affect the content of it).
If you can choose where the script tags go (e.g., you're not writing a JavaScript library or jQuery plug-in, your script is on a page you control), there's little if any reason to use ready. Instead, put your script tag at the end of the page, just before the closing </body> tag. References:
Google Closure engineers on when the DOM is ready
YUI Best Practices for Speeding Up your Website
The purpose of document.ready is to wait till the DOM is ready, if you put your scripts just before the body closing tag or just after the html that is being modified then you don't need document.ready although it should still work.
This will work but it is bad practice. If you can you should put your scripts at the end of your webpage rather than in the head. Unless of course you have something (like a document ready function) that you need to load first.
I mean : I know the JS is cached only if it come from a .js file. Also, 90% of my functions must be rendered when the page (html) is loaded (rendered), so it is better put JS before closing the body tag. (this prevent also to use document .ready(); and the loading of the page itself will be more faster).
So, which is the advantage on putting JS in the <head></head>? Expect the "order" of the code, which I don't mind so much to be honest...
Placing a <script src> tag inside the <head> section makes sense – semantically. It does block the browser from rendering anything until the script is loaded but assures that an object (e.g. jQuery) is available in the rest of your code (in the body for example).
A common practice is to load a light weight script loading library (HeadJs, LABjs, etc) inside the head section, then load the heavy stuff lazily and/or on-demand.
Having said that, HTML5 introduced the async attribute for script tags and re-introduced the defer attribute (docs). So you now have a very good and valid reason for putting <script src> tags inside head sections because:
it makes sense
the script still loads after the page has finished loading
The <script> tag causes two problems:
Everything below the script won't render until the script is loaded.
All components below the script don't start downloading until the script is done.
Putting it into the <head> only really makes sense if you need to execute some JavaScript before anything gets rendered.
So placing it as low as possible in the page would result in a better user experience.
It's slightly more semantic to put it in the header, but it doesn't generally have any advantages. Sometimes it is necessary - for example, loading fonts using JavaScript (using stuff like Google Webfonts) has to be done in the header, or the page will render with the wrong font and then change, which won't look good to the user.
The important thing about the elements in the <head> section are that they are loaded, before the <body> starts to load.
This is a very efficient feature, which are used a lot (IMO).
Loading of libraries, scripts, that have to run before the DOM has loaded have to done in <head> section.
I will give you a scenario
Imagine, You needed to calculate the 30% size of the screen's total size and assign it to the element inside.
It would be foolish and wait for the element to load big, then run the script to load resize it again.