Where to place JavaScript in an HTML file? - javascript

Say I have a fairly hefty JavaScript file, packed down to roughly 100kb or so. By file I mean it’s an external file that would be linked in via <script src="...">, not pasted into the HTML itself.
Where’s the best place to put this in the HTML?
<html>
<head>
<!-- here? -->
<link rel="stylesheet" href="stylez.css" type="text/css" />
<!-- here? -->
</head>
<body>
<!-- here? -->
<p>All the page content ...</p>
<!-- or here? -->
</body>
</html>
Will there be any functional difference between each of the options?

The Yahoo! Exceptional Performance team recommend placing scripts at the bottom of your page because of the way browsers download components.
Of course Levi's comment "just before you need it and no sooner" is really the correct answer, i.e. "it depends".

The best place for it is just before you need it and no sooner.
Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.
Is your js script a commonly used lib like jQuery or prototype? If so, there are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.

As a rule of thumb, the best place to put <script> tags is the bottom of the page, just before </body> tag. Something like this:
<html>
<head>
<title>My awesome page</title>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="...">
<link rel="stylesheet" type="text/css" href="...">
<link rel="stylesheet" type="text/css" href="...">
<link rel="stylesheet" type="text/css" href="...">
</head>
<body>
<!-- Content content content -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="..."></script>
<script type="text/javascript" src="..."></script>
<script type="text/javascript" src="..."></script>
</body>
</html>
Why?
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. More...
CSS
A little bit off-topic, but... Put stylesheets at the top.
While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively. More...
Further reading
Yahoo have released a really cool guide that lists best practices to speed up a website. Definitely worth reading:
https://developer.yahoo.com/performance/rules.html

With 100k of Javascript, you should never put it inside the file. Use an external script Javascript file. There's no chance in hell you'll only ever use this amount of code in only one HTML page. Likely you're asking where you should load the Javascript file, for this you've received satisfactory answers already.
But I'd like to point out that commonly, modern browsers accept gzipped Javascript files! Just gzip the x.js file to x.js.gz, and point to that in the src attribute. It doesn't work on the local filesystem, you need a webserver for it to work. But the savings in transferred bytes can be enormous.
I've successfully tested it in Firefox 3, MSIE 7, Opera 9, and Google Chrome. It apparently doesn't work this way in Safari 3.
For more info, see this blog post, and another very ancient page that nevertheless is useful because it points out that the webserver can detect whether a browser can accept gzipped Javascript, or not. If your server side can dynamically choose to send the gzipped or the plain text, you can make the page usable in all web browsers.

Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.
You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.

Using cuzillion you can test the affect on page load of different placement of script tags using different methods: inline, external, "HTML tags", "document.write", "JS DOM element", "iframe", and "XHR eval". See the help for an explanation of the differences. It can also test stylesheets, images and iframes.

The answer is depends how you are using the objects of javascript. As already pointed loading the javascript files at footer rather than header certainly improves the performance but care should be taken that the objects which are used are initialized later than they are loaded at footer. One more way is load the 'js' files placed in folder
which will be available to all the files.

The scripts should be included at the end of the body tag because this way the HTML will be parsed by the browser and displayed before the scripts are loaded.

The answer to the question depends. There are 2 scenarios in this situation and you'll need to make a choice based on your appropriate scenario.
Scenario 1 - Critical script / Must needed script
In case the script you are using is important to load the website, it is recommended to be placed at the top of your HTML document i.e, <head>. Some examples include - application code, bootstrap, fonts, etc.
Scenario 2 - Less important / analytics scripts
There are also scripts used which do not affect the website's view. Such scripts are recommended to be loaded after all the important segments are loaded. And the answer to that will be bottom of the document i.e, bottom of your <body> before the closing tag. Some examples include - Google analytics, hotjar, etc.
Bonus - async / defer
You can also tell the browsers that the script loading can be done simultaneously with others and can be loaded based on the browser's choice using a defer / async argument in the script code.
eg. <script async src="script.js"></script>

Like others have said, it should most likely go in an external file. I prefer to include such files at the end of the <head />. This method is more human friendly than machine friendly, but that way I always know where the JS is. It is just not as readable to include script files anywhere else (imho).
I you really need to squeeze out every last ms then you probably should do what Yahoo says.

Your javascript links can got either in the head or at the end of the body tag, it is true that performance improves by putting the link at the end of your body tag, but unless performance is an issue, placing them in the head is nicer for people to read and you know where the links are located and can reference them easier.

I would say that it depends of fact what do you planed to achieve with Javascript code:
if you planned to insert external your JS script(s), then the best
place is in head of the page
if you planed to use pages on smartphones, then bottom of page,
just before tag.
but, if you planned to make combination HTML and JS (dynamically
created and populated HTML table, for example) then you must put
it where you need it there.

Related

Why Calling Jquery At Head Of Page Solve Most Of My Problems? [duplicate]

Say I have a fairly hefty JavaScript file, packed down to roughly 100kb or so. By file I mean it’s an external file that would be linked in via <script src="...">, not pasted into the HTML itself.
Where’s the best place to put this in the HTML?
<html>
<head>
<!-- here? -->
<link rel="stylesheet" href="stylez.css" type="text/css" />
<!-- here? -->
</head>
<body>
<!-- here? -->
<p>All the page content ...</p>
<!-- or here? -->
</body>
</html>
Will there be any functional difference between each of the options?
The Yahoo! Exceptional Performance team recommend placing scripts at the bottom of your page because of the way browsers download components.
Of course Levi's comment "just before you need it and no sooner" is really the correct answer, i.e. "it depends".
The best place for it is just before you need it and no sooner.
Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.
Is your js script a commonly used lib like jQuery or prototype? If so, there are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.
As a rule of thumb, the best place to put <script> tags is the bottom of the page, just before </body> tag. Something like this:
<html>
<head>
<title>My awesome page</title>
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="...">
<link rel="stylesheet" type="text/css" href="...">
<link rel="stylesheet" type="text/css" href="...">
<link rel="stylesheet" type="text/css" href="...">
</head>
<body>
<!-- Content content content -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="..."></script>
<script type="text/javascript" src="..."></script>
<script type="text/javascript" src="..."></script>
</body>
</html>
Why?
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. More...
CSS
A little bit off-topic, but... Put stylesheets at the top.
While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively. More...
Further reading
Yahoo have released a really cool guide that lists best practices to speed up a website. Definitely worth reading:
https://developer.yahoo.com/performance/rules.html
With 100k of Javascript, you should never put it inside the file. Use an external script Javascript file. There's no chance in hell you'll only ever use this amount of code in only one HTML page. Likely you're asking where you should load the Javascript file, for this you've received satisfactory answers already.
But I'd like to point out that commonly, modern browsers accept gzipped Javascript files! Just gzip the x.js file to x.js.gz, and point to that in the src attribute. It doesn't work on the local filesystem, you need a webserver for it to work. But the savings in transferred bytes can be enormous.
I've successfully tested it in Firefox 3, MSIE 7, Opera 9, and Google Chrome. It apparently doesn't work this way in Safari 3.
For more info, see this blog post, and another very ancient page that nevertheless is useful because it points out that the webserver can detect whether a browser can accept gzipped Javascript, or not. If your server side can dynamically choose to send the gzipped or the plain text, you can make the page usable in all web browsers.
Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.
You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.
Using cuzillion you can test the affect on page load of different placement of script tags using different methods: inline, external, "HTML tags", "document.write", "JS DOM element", "iframe", and "XHR eval". See the help for an explanation of the differences. It can also test stylesheets, images and iframes.
The answer is depends how you are using the objects of javascript. As already pointed loading the javascript files at footer rather than header certainly improves the performance but care should be taken that the objects which are used are initialized later than they are loaded at footer. One more way is load the 'js' files placed in folder
which will be available to all the files.
The scripts should be included at the end of the body tag because this way the HTML will be parsed by the browser and displayed before the scripts are loaded.
The answer to the question depends. There are 2 scenarios in this situation and you'll need to make a choice based on your appropriate scenario.
Scenario 1 - Critical script / Must needed script
In case the script you are using is important to load the website, it is recommended to be placed at the top of your HTML document i.e, <head>. Some examples include - application code, bootstrap, fonts, etc.
Scenario 2 - Less important / analytics scripts
There are also scripts used which do not affect the website's view. Such scripts are recommended to be loaded after all the important segments are loaded. And the answer to that will be bottom of the document i.e, bottom of your <body> before the closing tag. Some examples include - Google analytics, hotjar, etc.
Bonus - async / defer
You can also tell the browsers that the script loading can be done simultaneously with others and can be loaded based on the browser's choice using a defer / async argument in the script code.
eg. <script async src="script.js"></script>
Like others have said, it should most likely go in an external file. I prefer to include such files at the end of the <head />. This method is more human friendly than machine friendly, but that way I always know where the JS is. It is just not as readable to include script files anywhere else (imho).
I you really need to squeeze out every last ms then you probably should do what Yahoo says.
Your javascript links can got either in the head or at the end of the body tag, it is true that performance improves by putting the link at the end of your body tag, but unless performance is an issue, placing them in the head is nicer for people to read and you know where the links are located and can reference them easier.
I would say that it depends of fact what do you planed to achieve with Javascript code:
if you planned to insert external your JS script(s), then the best
place is in head of the page
if you planed to use pages on smartphones, then bottom of page,
just before tag.
but, if you planned to make combination HTML and JS (dynamically
created and populated HTML table, for example) then you must put
it where you need it there.

What is the best place to put <script> tag in a JSP file?

I have a bunch of JSP files and around 10-12 javascipt files which I am including in every JSP file using the include tag as follows:
<%# include file="common_js_files.jsp"%>
I have already seen Where should I put <script> tags in HTML markup?
As per the answers given, many agreed to place the <script> tags just before the closing body tag. I was expecting this would reduce the page loading time, however it didn't change the loading time. Is the case mentioned in the above link only for HTML pages ? What about JSP pages ?
Kindly suggest if there is a better way of handling such common javascript files in JSP pages.
Thanks in advance.
The old approach to solve this problem was to put tags at the bottom of your , because this ensures the parser isn't blocked until the very end.
This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts & stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.
In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.
The modern approach
Today, browsers support the async and defer attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.
async
<script type="text/javascript" src="path/to/script1.js" async></script>
<script type="text/javascript" src="path/to/script2.js" async></script>
Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.
This implies that it's possible script 2 is downloaded & executed before script 1.
According to http://caniuse.com/#search=async, 80% of all browsers support this.
defer
<script type="text/javascript" src="path/to/script1.js" defer></script>
<script type="text/javascript" src="path/to/script2.js" defer></script>
Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.
Unlike async scripts, defer scripts are only executed after the entire document has been loaded.
According to http://caniuse.com/#search=defer, 80% of all browsers support this. 88% support it at least partially.
An important note on browser compatibility: in some circumstances IE <= 9 may execute deferred scripts out of order. If you need to support those browsers, please read this first!
Conclusion
The current state-of-the-art is to put scripts in the tag and use the async or defer attributes. This allows your scripts to be downloaded asap without blocking your browser.
The good thing is that your website should still load correctly on the 20% of browsers that do not support these attributes, while speeding up the other 80%.
Source
In the browser JSP will be converted to/interpreted as HTML, so the best practices are the same for both JSP and HTML, saying that:
Many web developers recommend loading JavaScript code at the bottom of the page to increase responsiveness, and this is even more important with the HTML service. In the NATIVE sandbox mode, all scripts you load are scanned and sanitized client-side, which may take a couple of seconds.
Moving your tags to the end of your page will let HTML content render before the JavaScript is processed, allowing you to present a spinner or other message to the user.
And for further reading take a look at :
HTML Service: Best Practices, "Load JavaScript last" section.
Best Practice: Where to include your tags.

Is there a way to load specific features from jQuery in real time?

As I can see, loading jQuery every time I load a site is pretty slow. i.e.
<!-- jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- Site Scripts -->
<script type="text/javascript" src="js/myJS.js"></script>
Compared to downloading jQuery to my local file system and import it locally. i.e.
<!-- jQuery -->
<script type="text/javascript" src="js/jquery-someversion.min.js"></script>
<!-- Site Scripts -->
<script type="text/javascript" src="js/myJS.js"></script>
Obviously depends on my internet's speed at the time of loading the script.
I was wondering if there is a jQuery API of some sort that would allow me to "lazy load" it(jQuery) using HTML script tag. What I mean with lazy loading jQuery is: loading only the specific feature(s) I'm going to use, i.e.
<!-- jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js/events"></script>
<!-- Site Scripts -->
<script type="text/javascript" src="js/myJS.js"></script>
Changed the source: < script .... src="http://code.jquery.com/jquery-latest.min.js/events"/ >
I know that I can look up for the jQuery code of that specific feature and load it myself when needed, but I do NOT want to copy the features into my local file system every time jQuery has an update or whatever. If you are still not getting where I'm going, what I want is to have a way in which I know that the features are UP TO DATE and SUPPORTED (by jQuery) so later bug-fixes/improvements/changes/additions/cross-browser-support to jQuery are "automagically" implemented in my site.
if you will use a cdn path, then it will not redownload the file if it has been cached previously. It increases the chance that there will be a cache-hit.
(As more sites follow this practice, more users already have the file ready.)
You can create your own build of jQuery but you will have to host it yourself.
Follow the "How to build your own jQuery" guide for instructions:
Special builds can be created that exclude subsets of jQuery functionality. This allows for smaller custom builds when the builder is certain that those parts of jQuery are not being used. For example, an app that only used JSONP for $.ajax() and did not need to calculate offsets or positions of elements could exclude the offset and ajax/xhr modules.
You're always going to be slower fetching jquery-latest vs jquery-version--the server enforces it. For example:
http://code.jquery.com/jquery-latest.min.js
http://code.jquery.com/jquery-1.10.2.min.js
Note that there is now a very future dated Expires header sent. That means that once the first page is loaded, the browser is going to cache this version for a very long time making subsequent page calls have [almost] no latency.
By staying with the latest, however, you're forcing the browser to fetch this file for every page load. Of course that's going to add latency.
what I want is to have a way in which I know that the features are UP TO DATE and SUPPORTED (by jQuery) so later bug-fixes/improvements/changes/additions/cross-browser-support to jQuery are "automagically" implemented in my site.
Except when you write something that uses $.browser, .die() or .live then wonder why it's no longer working.
There's something to be said for spending the few minutes and updating your JS files (especially if it means your site worked yesterday and doesn't today and you don't know why).
You don't say so! jQuery's size is only 32KB!
http://code.jquery.com/jquery-latest.min.js
You will spent much more time loading multiple files than one. Furthermore, it will be a good idea to merge all you JS and CSS files into one JS and one CSS file.

javascript parallel loading

I heard that javascripts files on web pages were not downloaded parallelly, so I did some experiment on firefox using firebugs. However, I did see javascripts were donwloaded in parallel, and my web page included sripts in old fasion way:
<head>
<meta charset="utf-8" />
<title>Home Page</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
</head>
Since the article I read was written in 2009, I am wondering if anything changed after, or did firefox did the javascripts loading in different way??
Thanks
Browsers will download resources (images, scripts, frames, etc...) in parallel (up to some max number of them concurrently), but some resources such as script resources are not safe to be parsed and executed in parallel because they may have been written to execute in a particular order.
So, while the browser can load script tags in parallel, it waits until it can execute them in sequence (assuming they are normal inline script tags without any special attributes like "defer" or "async"). But, even in those cases (except for webworkers which isn't what is being discussed here), javascript is single threaded so only one piece of javascript will execute at a time.
It's not about the downloading, but about the parsing and executing. If the second Javascript file depends on some global variable set in the first Javascript file, then it cannot be executed and not even fully parsed before the first one is loaded. Since there is no easy way for a Browser do determine if there are such dependencies, the safe way is to parse and execute the files sequentially.
Since there is the possibility to do document.write() commands and to generally alter the DOM, while the Javscript is parsed and executed, parsing and rendering of the HTML has to wait, too.
There are hacks such as this that will dynamically add a new script definition, which is loaded and parsed in parallel. More elegant is the defer attribute, but the browsers do not all handle it the same.
Usually scripts are not loaded in parallel, since sometimes loading order is important.
The script elements block progressive page downloads. Browsers download several
components at a time, but when they encounter an external script, they stop further
downloads until the script file is downloaded, parsed, and executed.
However, there are ways to allow downloading of scripts in parallel:
As a side note, there are some common attributes developers tend to use with the
<script> element:
[...]
defer
(And better yet, HTML5’s async) is also a way, albeit not widely supported, to
specify that downloading the external script file shouldn’t block the rest of the
page.

Where should JavaScript be put?

I've been doing a little JavaScript (well, more like jQuery) for a while now and one thing I've always been confused about is where I should put my scripts, in the <head> tag or in the <body> tag.
If anyone could clarify this issue, that'd be great. An example of what should go where would be perfect.
Best practices from google and yahoo say that, for performance, javascript should always be put in an external file, and linked to your page with a <script> tag located at the bottom of the html, just before the closing of the <body> element.
This allows the browser to render the entire page right away, instead of stopping to evaluate javascript.
You mentioned three places:
In tags;
In the HTML; and
In an external file.
Let me address each of those.
Best practice is to have common Javascript in one or more external files and the less files the better since each JS file loaded will block loading of the page until that JS file is loaded.
The word "common" is extremely important. What that means is you don't want to put page-specific Javascript code in that external file for caching reasons. Let's say you have a site with 1000 pages. Each page has JS code specific to it. That could either be 1000 different files or one really big file that executes a lot of unnecessary code (eg looking for IDs that aren't on that particular page but are on one of the 999 others). Neither of these outcomes is good.
The first gives you little caching boost. The second can have horrific page load times.
So what you do is put all common functions in one JS file where that JS file only contains functions. In each HTML page you call the JS functions needed for that page.
Ideally your JS files are cached effectively too. Best practice is to use a far futures HTTP Expires header and a version number so the JS file is only loaded once by each browser no matter how many pages they visit. When you change the file you change the version number and it forces a reload. Using mtime (last modified time of the JS file) is a common scheme, giving URLs like:
<script type="text/javascript" src="/js/script.js?1233454455"></script>
where that mtime is automatically generated. Your Web server is configured to serve JS files with an appropriate Expires header.
So that mixes external files and in-page scripts in (imho) the best way possible.
The last place you mentioned was in the tag. Here it depends somewhat on what JS libraries and frameworks you use. I'm a huge fan of jQuery, which encourages unobtrusive Javascript. That means you (hopefully) don't put any Javascript in your markup at all. So instead of:
do stuff
you do:
do stuff
with Javascript:
$(function() {
$("#dostuff").click(doStuff);
});

Categories