Placing Javascript in a HTML file [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How bad is it to embed JavaScript into the body of HTML?
Ok, so I've been using JavaScript for a good while now and I'm no stranger to it, but my question is in regards to where the JavaScript should actually be placed in a HTML file.
I've always been told and worked under the impression that all of your references to external script files should be contained in the head tag and any script that is contained in the current HTML file should be at the end of the file.
Now, more recently and having discussions with co-workers I have seen more and more people placing script blocks in seemingly random places throughout the HTML page, such as
<div>
<p>Foo</p>
<script type="text/javascript">
//some script
</script>
<p>Bar</p>
</div>
Now is this good practice? I've always thought that it wasn't. If so, is it beneficial because the script gets executed at that point, but then why can't you wait until the rest of the HTML has been loaded?

+1 vote for at the bottom of the page
give visitors the;
content and markup first
then display with css
then ui with javascript
appreciate this is a tad high brow

Scripts should be placed at the bottom of the page, as that will allow all of the sites resources, such as images, to download in parallel. Once finished the scripts will then be downloaded, one at a time.
The reason it's better to place scripts at the bottom of the page, is because they block parallel downloads. Normally the browser downloads resources such as images in parallel, two resources at a time (as specified by the HTTP 1.1 specification), per hostname. Scripts stop this from happening and will not allow anything else to download until after they have been fully downloaded.

Duplicate of this Question
Is it bad practice to embed JavaScript into the body of HTML?
It is helpful (and perfectly valid) sometimes when you want to ensure that certain dom is created before the script is run.

When I use inline, It has an obvious benefit, for me. for example.
(I will try to explain it with basic scenario. so don't be critical about the scenario)
I have A,B and C html sections (divs) in my page. obviously I will render them all, but I want only one section visible at a time to a visitor. so I can't wait for the whole page and javascript files to be loaded and then apply the "set visibility priority for section" javascript method to fire. because in the meanwhile all three sections (A,B and C) will remain visible until everything is not fully loaded. and the page might look awful so I prefer to use inline javascript.

Started to write a comment underneath Rob Sedge's reply, but it grew larger...
1) CSS at top, in the header (unless you want the user to see page without styling, for large HTML files / external JS, where loading times can be extensive)
2) Content and markup in the body
3) JS in the footer, before </body>
Even though currently JS evaluation is strongly suggested to occur within $(document).ready, or $(window).load events, some external scripts might not do that - in such case they will be evaluated as soon as the content has been downloaded, often causing a random behavior. Furthermore , content is evaluated as soon as browser actually processes given tag (point 1), thus additional fun stuff.
An additional (and at least for me main) point is this - let's say that you've got a templating engine, or PHP inclusion in your documents. Now - let's say that you've got a lot of such files, and in one of them JS code needs to be changed. In such cases, if you're not the only person working on a project, you'd need to search for given bit of code in all of those files. Thus - keeping JS in one place is good practice.
Let's add to that, that if you indeed keep your JS code in one place, then such content can be minified or cached, allowing for faster loading of the site overall. Why indeed you'd want the user to download your bit of JS every time the page is loaded, when that script can be evaluated from the cache. If you separate your scripts, such approach becomes hard.

Basically, the scripts that you put on the header, are downloaded synchronously, and you can be sure that they ar going to be executed in order, but if don't need those scripts to be executed before the page finishes loading, maybe you prefeer to include them at the bottom, or in a deferred way, to finish render the page more quickly, and give the users a better experience.
About the scripts contained in the HTML, it depends on what they do. For example, if for some reason you need to do a Document.write, or you want to execute some code before the page is rendered, to modify the DOM, they are very handy.
I strongly recomend you to read the two books of Steve Souders: "High Performance Web Sites" and "Even Faster Web Sites", there you have a very good explanation on the differences.

Related

"JavaScript placed at the end of the document so the pages load faster" TRUE? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript on the bottom of the page?
I saw a comment in some twitter bootstrap example. It says
JavaScript placed at the end of the document so the pages load faster
Is this true?? If yes then How it works??
There are a number of advantages
There’s no need to have a check if the DOM is loaded, since by having
the scripts at the end, you know for sure it is.
A JavaScript script
file has to be loaded completely before a web browser even begins on
the next JavaScript file. The effect of this, if the JavaScript files
are included at the top of the document, is that it will be a visual
delay before the end user sees the actual page. This is completely
avoided if you include the JavaScript files at the end of the
document.
There are some limitations as well
While including the JavaScript files at the bottom helps us around the
problem of delaying the page rendering, thus giving the impression
that each page in the web site loads faster, it does have a drawback.
If the page is visible to the end user, but the JavaScript files haven’t finished loading yet, no events have been applied to the
elements yet (because everyone uses an unobtrusive approach, right?)
and the user might start clicking around and not getting the expected
results.
If you have proper fallbacks, e.g. a link element which gets content via AJAX if JavaScript is supported and the proper event has been
applied, otherwise it’s a normal link leading to another page, then
the problem isn’t that bad. Still somewhat annoying, though.
Useful Article Here
If the browser encounters a <script> tag, the HTMLRenderer will by default stop and the ECMAscript parser will do its job. The HTMLRenderer will not continue untill all the Javascript code was completely evalutated.
So, if you have many <script> tags and lots of Javascript code in your "upper" HTML code, a viewer of your site might realize a slow'ish loading process.
There are several ways to avoid this issues. The first is, as you mentioned, by just placing all the Javascript code and <script> tags at the very bottom of the <body> element. That ensures that at least all the HTML markup and Stylesheet definitions were fully loaded.
Another options are tag names for the <script> element itself. Such as async and defer will indicate to the Browser / JS Parser that this fill is not required to get loaded and evaluated immediately. For instance
<script async defer src="/foo/bar.js"></script>
The HTML Renderer will realize the tag and store it into a queue, but it will not directly stop and evaluate.
Most browsers execute JavaScript and load the page using the same thread. Hence while JavaScript is executing the page cannot load. Thus if you page contains lots of images or embedded content these assets will not start loading until the JavaScript completes execution.
This is the reason it's advised to put long running synchronous code at the end of the document, or defer it to load when the page loads or the DOM content loads. However modern browsers usually notify the user about long running blocking scripts and allow them to terminate the script if desired.
As important as placing them at the end of the page, is specifying them as async using the HTML5 async attribute. This will ensure that the parser does not stop and parse them but rather continues with the page loading flow and downloads/parses the JS in parallel.
http://davidwalsh.name/html5-async
The logic behind that concept is that since the browser renders your code on the fly, by placing all the html elements before the scripts, it could theoretically load faster than if you had the scripts first, assuming you had an astronomical amount of scripts to deal with.
In practise however no one should ever encounter a situation that would require so much script time that it would affect the load time of a website over more pressing bottlenecks as D/L bandwidth.

JavaScript Best Practices: where should I include my JavaScript?

I am building a website using PHP and JavaScript, and I feel that I have a good grasp on where to include my JavaScript, but a more specific situation has come up that has me confused. I currently have all of my JavaScript in one external file, which is being included on every PHP page.
Let's say that I have a paragraph with an id='myParagraph' and I need to highlight this paragraph in red with JavaScript on page load. This paragraph is only on ONE PHP page and my website has about 50 different pages. I immediately assumed that I should throw some code into my one external JavaScript file, something like:
$('#myParagraph').css('color', 'red')
and the paragraph would be highlighted when that page loads.
My question is: is this the best way to do it? To my understanding, every time I load a page it will be searched for an element with the id myParagraph, yet 98% of my pages won't even have that id. Is this wasteful? Should I instead include the following code:
function highlightParagraph()
{
$('#myParagraph').css('color', 'red')
}
in my one JavaScript file and then put some inline JavaScript in the PHP file with the id myParagraph to call the function highlightParagraph() when it's loaded? That way, only the one page with myParagraph will be searched and highlighted.
I feel like option 2 is the best, but I read all the time not to use inline JavaScript.
edit: I realize that for this example you would just use CSS. I'm just using it to get my question across
You should have a one "big" js file with the infrastructure functions and all the pages should have a reference to it.
Then each page should reference another js file with the functions related only.
The good things about using external js files are:
The files are cached after the first download => Faster surfing.
Separate of concerns, you keep the presentation tier away from the scripting tier.
Another important note:
The best way to change css is with css... not javascript.
I
If you change the element style on DOM ready, just add the element definition
#myParagraph{color: red;}
The problem with inline JavaScript is you might be starting with a few lines now, but in a few weeks or months, it will add up and be a lot of inline JavaScript.
That is bad, because inline JavaScript can't be cached by the browser like JavaScript files that you include with <script src="path/to/file.js" />.
That's bad because you add a lot of content that will be fetched every single page view by the user, adding load on your server bandwidth and slowing page load for the user.
If it's just a few selectors, don't worry; The time wasted on it won't cause any browser to sweat.
Though, if it becomes a lot of code for a different page/module of your site, you might want to split it into a different JavaScript file and include just that file when certain pages are loaded.
That way, the browser will cache that file and save that bandwidth for you and the user.
I wouldn't be too surprised if many people disagree with me (violently even) but I don't have a problem with putting a javascript tag with specific javascript for that page in the header if it will reduce the number of files or overall complexity of the project. Most of the core things that are done everywhere should of course be separated in another file but if it is a one page deal, then I would go for cleanliness.
The same goes for css, if it is specific to that page just put a css tag in the header with the specific changes that differ from the master css file. BTW as everyone is pointing out, this is a case where you want to just use CSS.

Where should I include javascript on a page?

I am building a Rails app, and it seems that common practice is to have javascript_include_tags listed on top of a page.
Would it makes browers load javascript before loading the document, and thus makes visible elements take longer to load?
Thank you.
As far as I've read on the web, best practice loads javascript files at the bottom of the body tag. This lets almost everything load before executing the javascript, which generally prevents problems accessing items that may not exist if you loaded the script at the top.
A Yahoo post about web page performance suggests including them at the bottom of the page (Source) because they can block parallel downloads of other dependencies if they are at the top.
Looks like some answers were right, but none sums it all up:
How to prevent javascript loading from loading other elements? Simple, put it right before the closing </body> tag. Which usually means a few characters before the end of your HTML page.
Put all your javascript in external .js files. Why? So that the browsers can cache those files even when the HTML page changes.
Aggregate and minify all your javascript files into one. Why? Because the fewer HTTP requests your clients make, the faster the page loads.
Also, you don't have to care about $(document).ready() or window.onload, since all your HTML elements will be loaded before the javascript files (that is, if you put the JS files right before the closing </body> tag).
It's a good idea to use external JS file and to minify it's content.
http://www.quirksmode.org/js/placejs.html
Bottom of the page is also an option like John Fisher said.
If using i.e. jQuery you in any case use $() or $(document).ready(function() which makes sure the page DOM is loaded before you try to use your JS functions.
Rather than embedding the behavior in its markup, try to segregate the script
by moving it to a script block in the section of the page, outside the scope of the
document body, as follows:
<script type="text/javascript">
window.onload = function() {
document.getElementById('testButton').onclick = function() {
document.getElementById('xyz').style.color = 'red';
};
};
</script>
For performance reasons, script blocks can also be placed at the bottom
of the document body, though modern browsers make the performance
difference rather moot. The important concept is to avoid embedding behavioral
elements within the structural elements.

Is it practically good to put JS files at the bottom of webpage?

It is widely recommended that JS files should be put at the bottom of page to allow html codes to be loaded first. In this case, visitors will see something when waiting for full load of the page. However, I think this is disadvantageous for these reasons:
Modern design mainly depends on JS. This means before loading JS, the page will look ugly.
If interrupting the connection during the load (not loading JS at all), visitors will miss some of the website features (probably very important); and they will not understand that this is the problem of load (to re-load the page).
If the server-side script die (due to an error) at the very end of script before footer (e.g. in PHP), visitors will miss the whole page functionality (by JS); but if loading JS at the top, they will only miss the footer or half the page.
If loading JS first, browser will load other stuff (like images) in parallel; but if loading JS last, it may increase the load time. Because JS files are large (e.g. JQuery and JQuery UI), and all tiny stuffs (like images) have been loaded and we are loading a large file, last in line.
UPDATE: 5. Since jQuery library should be loaded before codes; if loading the jQuery library in footer (e.g. footer.php), you cannot add custom jquery codes for different pages (within the body).
Please correct me if I'm wrong! Is putting JS files in footer still beneficial?
Edit: I am adding another point in response to the cotton I'm seeing in peoples ears on this topic.
Additional point #5. If you are seriously concerned about handling behavior on JS-fail and by that I mean, people browsing with JS turned off, what you should be doing is embracing the notion of progressive enhancement. For instance, you could design an accordion menu to act as a flyout-menu on-hover by default, yes with CSS only, and then remove that behavior by changing key classes when JS is enabled. That way users have access to the links without JS if they should turn it off but they get the enhanced behavior when JS is working.
But what you should not be trying to handle is the absence of entire JS files on pages that are supposed to have them because the page was mangled on the back-end. Handling the unexpected is one thing, but handling the failure to finish building an HTML file before it's served should not ever be considered an acceptable scenario in production, especially if you have actual back end code in your templating language (which you shouldn't) waiting to spill out and give would-be hackers something potentially interesting to look at. Broken pages should be served as error messages.
================================
Dead wrong. Any time you use JS to tweak the initial static look of your page, you're doing it wrong. Maintain that separation of concerns and your pages will be much more flexible. Using JS to tweak the STATIC styles of your pages isn't modern, it's bass-ackwards and you can tell the jQuery mobile guys I said as much. If you absolutely must support IE6 and IE7 and IE8 tell your client how much it's going to cost them to cut out rounded gradient corners all over the place if they refuse to accept anything as an alternative to absolute graceful degradation for 5% of their client-base.
If your pages, with no JS beforehand are taking that long to load, you have other problems that need to be addressed. How many resources are you loading? What ungodly pre-processing is your PHP up to? I call back end or design shenanigans.
Are you saying it's half-acceptable to have half a page with working JS rather than completely unacceptable? Don't let go of that client, whoever they are.
jQuery, when minimized is about the size of a medium-sized JPEG.
Note: It is not entirely unacceptable to have some JS up top. Some specialized code like analytics stuff or canvas normalizers require it. But anything that doesn't need to be should be at the bottom. Every time JS is parsed, the entire page load and flow calculation process stalls out. Pushing your JS to the bottom improves perceived page load times and should also serve to provide evidence that somebody on your team needing a swift kick in the butt to figure out why their code is tanking or what could be done with their 25 megabyte png-24s that they just shrunk down rather than reformatted.
Script tags in the header block all other requests. If you have let's say 10 tags like this:
<script src="http://images.apple.com/home/scripts/promotracker.js"></script>
...they will be executed sequentially. No other files will concurrently be downloaded. Hence they increase page load time.
Check out HeadJS here as a sample solution.
You need to think in terms of "do I need the DOM to be ready before I execute some javascript". Basically you put script tags at the bottom of the page to basically guarantee that the DOM is ready. If you link your styling in the header, and properly style the page, you shouldn't get the "ugliness". Secondly, if you are dependent on some parts of the page to be displayed with javascript to work on DOM objects, I would use more ajax calls to prevent this problem as well. The best of both worlds. Page is loaded with what you can, and then ajax calls are getting the html to populate on other parts of the page.
The reason putting JS at the bottom of the page or loading in asynchronously is recommended is that JS slows the page load down.
If some browsers downloading the JS blocks other parallel downloads, and in all browsers executing the JS blocks the UI thread and hence rendering (parsing blocks in some too).
Putting it a the bottom or loading asynchronously attempts to delay the issue until it has less impact on the visitors page load experience.
Don't forget that no matter how beautiful you page is, is it takes too long to load people won't wait and 2 /3 seconds is where it starts to cause problems.
Modern design can probably depends less on JS that it ever has - yes we need polyfills still but as browsers get better then we can do more with CSS
This might be true for things like Backbone.js apps, but if the lack of JS breaks the site then I'd argue the design should be different.
If the server-side script dies there are perhaps other issues to worry about, there's no guarantee there's enough of the page to be useful anyway.
NO! JS blocks the UI thread and in some cases downloads so the images will be delayed. Also as the JS is using connections then there are less connections available for parallel downloads.
Have a look at #samsaffron's article on loading jQuery late - http://samsaffron.com/archive/2012/02/17/stop-paying-your-jquery-tax
If you can delay the JS load you should
I have occasionally recommended putting Javascript at the bottom of a page (just before </body>) but only in circumstances where a novice programmer couldn't really cope with window.onload or <body onload...> and that was the easiest adaptation of their code to get it to work.
I agree with your practical disadvantages, which need to be balanced against Michael's note of the effect on load time. In most cases [I submit] loading scripts in the <head> of the page wins.
Everybody's needs are different, lets go through your list:
1) I've never had an issue with the layout or styling of the page because of javascript. If you have your HTML & CSS in order the missing javascript will be close to invisible.
You can hide elements in the css and display them with javascript when they're ready. You can use jQuery's .show(); method
here's an example:
<!DOCTYPE html>
<html>
<head>
<style>
div { background:#def3ca; margin:3px; width:80px;
display:none; float:left; text-align:center; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button id="showr">Show</button><button id="hidr">Hide</button>
<div>Hello 3,</div><div>how</div><div>are</div><div>you?</div>
<script>
$("#showr").click(function () {
$("div").first().show("fast", function showNext() {
$(this).next("div").show("fast", showNext);
});
});
$("#hidr").click(function () {
$("div").hide(1000);
});
</script>
</body>
</html>
If you still have problems you can split up your javascript into ones your site relies on and other scripts and put some in the header and some in the footer.
2) That's user error, you can't control that, but you could check if the needed functionality is there and attempt to reload it. Most plugins offer some sort of confirmation if they're running or not, so you could run a test and try to reload them.
You can also delay loading of files until the user needs them, like waiting for them to focus on a form to load validation scripts or scroll past a certain point to load the code for things below "the fold"
3) If the page dies you're going to get a half-blank page anyhow. With PHP 5 you can do better error handling with exceptions
if (!$result = mysql_query('SELECT foo FROM bar', $db)) {
throw new Exception('You fail: ' . mysql_error($db));
}
and this
try
{
// Code that might throw an exception
throw new Exception('Invalid URL.');
}
catch (FirstExceptionClass $exception)
{
// Code that handles this exception
}
catch (SecondExceptionClass $exception)
{
// you get the idea what i mean ;)
}
4) If you minify your script you they shouldn't be much larger than images. JQuery is 32KB minified & gziped. JQuery-UI's script is 51KB. That's not too bad, most plugins should be even smaller than that.
So I suggest you should do what you have to do to get the results you want, but search for best practices that reduce errors and excess code. There's always a better way to skin a cat...
I'm not really that familiar with putting the scripts in the footer, but you may want to look into the various ways of telling the page to only run the JavaScript AFTER the page is fully loaded.
This opens up a couple options - you could have JS dynamically load external scripts only after the page is ready.
You can also hide some or all of the page content, and then just make it visible after the page is ready. Just make sure you hide it with JS, so that non-js browsers can still see it.
See these:
https://www.google.com/search?q=javascript+page+ready
http://api.jquery.com/ready/

Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code?

I've recently read the Yahoo manifesto Best Practices for Speeding Up Your Web Site. They recommend to put the JavaScript inclusion at the bottom of the HTML code when we can.
But where exactly and when?
Should we put it before closing </html> or after ? And above all, when should we still put it in the <head> section?
There are two possibilities for truly unobtrusive scripts:
including an external script file via a script tag in the head section
including an external script file via a script tag at the bottom of the body (before </body></html>)
The second one can be faster as the original Yahoo research showed some browsers try to load script files when they hit the script tag and therefore don't load the rest of the page until they have finished. However, if your script has a 'ready' portion which must execute as soon as the DOM is ready you may need to have it in the head. Another issue is layout - if your script is going to change the page layout you want it loaded as early as possible so your page does not spend a long time redrawing itself in front of your users.
If the external script site is on another domain (like external widgets) it may be worth putting it at the bottom to avoid it delaying loading of the page.
And for any performance issues do your own benchmarks - what may be true at one time when a study is done might change with your own local setup or changes in browsers.
It's never so cut and dry - Yahoo recommends putting the scripts just before the closing </body> tag, which will create the illusion that the page loads faster on an empty cache (since the scripts won't block downloading the rest of the document).
However, if you have some code you want to run on page load, it will only start executing after the entire page has loaded. If you put the scripts in the <head> tag, they would start executing before - so on a primed cache the page would actually appear to load faster.
Also, the privilege of putting scripts at the bottom of the page is not always available. If you need to include inline scripts in your views that depend on a library or some other JavaScript code being loaded before, you must load those dependencies in the <head> tag.
All in all Yahoo's recommendations are interesting but not always applicable and should be considered on a case-by-case basis.
As others have said, place it before the closing body html tags.
The other day we had numerous calls from clients complaining their sites were extremely slow. We visited them locally and found they took 20-30 seconds to load a single page. Thinking it was the servers performing badly, we logged on - but both web and sql servers were ~0% activity.
After a few minutes, we realised an external site was down, which we were linking to for Javascript tracking tags. This meant browsers were hitting the script tag in the head section of the site and waiting to download the script file.
So, for 3rd party/external scripts at least, I'd recommend putting them as the last thing on the page. Then if they were unavailable, the browser would at least load the page up until that point - and the user would be oblivious to it.
To summarize, based on the suggestions above:
For external scripts (Google analytics, 3rd party marketing trackers, etc.) place them before the </body> tag.
For scripts that affect page layout, place in head.
For scripts that rely on 'dom ready' (like jquery), consider placing before </body> unless you have an edge-case reason to place scripts in head.
If there are inline scripts with dependencies, place the required scripts in head.
If you want to tinker with the position of your scripts, YSlow is a great tool for giving you a flavour if it's going to improve or hurt performance. Putting javascript in certain document positions can really kill page load times.
http://developer.yahoo.com/yslow/
No it should not be after the </html> as that would be invalid. The best place to put scripts is right before the </body>
This is basically because most browsers stop rendering the page while they eval the script that you provide. So its OK to put non-blocking code anywhere in the page (I'm mainly thinking of things that attach functions to the onLoad event, since event binding is so fast as to effectively be free). A big killer here is at the beginning of the page putting in some ad server script, which can prevent any of the page loading before the ads have totally downloaded, making your page load times balloon
If you put it at the bottom, it loads last, hence speeding up the speed that the user can see the page. It does need to be before the final </html> though otherwise it won't be part of the DOM.
If the code is needed instantly though, then put it in the head.
It's best to put things like blog widgets at the bottom so that if they don't load, it doesn't affect the usability of the page.

Categories