I have a webpage to be hosted on a mobile device which is both Wi-Fi and 3G capable.
As 3G data may cost money and is generally limited, i want to minimize the amount of uploaded data by the device. So what I basically want to do is the following:
Try to load the jquery scripts online:
<script type="text/javascript" src="http://code.jquery.com/ui/1.8.13/jquery-ui.min.js"></script>
And only if that fails to load correctly (e.g. if the user is not connected to the internet, just to the phone), load it from a local copy:
<script type="text/javascript" src="js/jquery-copy.js"></script>
The same applies for css files.
I've thought about having a <script id="loadable"></script> and then use $("#loadable").load("url"); but obviously I depend on jquery to be loaded first, which is the file to be minimized.
<script src="http://code.jquery.com/ui/1.8.13/jquery-ui.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/jquery-copy.js"%3E%3C/script%3E'))</script>
I edited the answer. I think bellow is the most elegant solution.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">window.jQuery || document.write('<script type="text/javascript" src="path/to/your/jquery"><\/script>')</script>
Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail
check out how they do it in HTML5 boilerplate.
If you take a look at the bottom of the index.html file within the GitHub repo, you'll see the following...
<script src="http://code.jquery.com/ui/1.8.13/jquery-ui.min.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/jquery-copy.js"%3E%3C/script%3E'))</script>
How does it work?
First, an attempt is made to grab the CDN version (Google's CDN url
is used above, but of course you could link to any source you like).
Immediately afterwards, we check for the jQuery global object.
If jQuery does not exist, the obvious assumption is that we didn't
manage to get the code from the CDN, so then we document.write a
script tag to get a copy from a local source instead.
Related
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.
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.
I am loading the following javascript files from a CDN. Is there any way I can check if these have been loaded correctly and if not, load them from a local folder?
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js
http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/jquery-ui.min.js
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js
I know I can check the jquery file but not sure about the others. Any tips?
In your HTML, you can do something like this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"><\/script>')</script>
The example shown is loading jquery from Google CDN and falls back on a local copy of JQuery if that fails.
Credits to HTML5 Boilerplate for showing the trick
YepNope.js is a more robust solution for loading resources (like js files), checking whether they've been loaded or not, and then providing a fallback if necessary. This is just 1 feature among many provided by the library.
I just checked my page size using firebug and all, and javascript files equal 478.2K!
<script src ="<%= Url.Content("/Scripts/MicrosoftAjax.js") %>"></script>
<script src ="<%= Url.Content("/Scripts/MicrosoftMvcAjax.js") %>"></script>
<script src ="<%= Url.Content("/Scripts/jquery-1.3.2.min.js") %>"></script>
<script src ="<%= Url.Content("/Scripts/jquery.form.js") %>"></script>
<script src ="<%= Url.Content("/Scripts/jquery.validate.js") %>"></script>
<script src ="<%= Url.Content("/Scripts/xVal.jquery.validate.js") %>"></script>
<script src ="<%= Url.Content("/Scripts/temp.js") %>"></script>
<script src ="<%= Url.Content("/Scripts/jquery-ui-1.8.5.custom.min.js") %>"></script>
<script src ="<%= Url.Content("/Scripts/jquery.ui.tabs.js") %>"></script
temp.js is my own file, and it has code of very few lines (like 10-20).
So what is going on? I mean how to fix this?
Start by getting rid of Microsoft*.js. If you use jquery you don't need those.
I would suggest that you use the minified versions of each js file and also that you combine them into one single js file (or as less as you can).
Here is an interesting article that may help you.
Except for temp.js (which you say is quite small), all the other files are third party libraries.
I assume you're using all those libraries on every page? If not, one thing you could do would be to only include them on pages where they're being used.
The file names suggest that some of them have been minimised. If the others haven't been, you could run them through a minimiser, or alternatively go back to their home pages to see if they supply a minimised version you could use.
Some of them may also provide an option on their site to only include functionality that you intend to use. JqueryUI does this for sure, though from the filename you're using it looks like you already made use of it for that, but check to see if any other libraries also offer that.
Check that you haven't got any overlapping functionality - you may be able to rationalise by removing redundant code. You would have to be very cautious if that means editing third party libraries (that's not usually a good idea), but you may find you've got entire libraries that are unnecessary, in which case it'd be a quick win to get rid of one of them.
If you want to off-load some of the scripts to a third party, Google hosts JQuery, JQueryUI and a lot of other plug ins, and they allow sites to load them from their servers. It wouldn't affect the size of the scripts that the user has to download, but would save your servers quite a lot of bandwidth.
At the end of the day though, you have got a lot of big scripts there, and they're providing a lot of functionality. If you need all that functionality, you'll have to put up with the weight of the code.
their are many thing you can do for this situation
use minified or production version instead of developer version
load them from CDN if you can do that.
If files not been changes from long time that you need TO use Cache.
their are many other thing you can do for application performance improvement.
You could try gzip compression so that the server compresses it and is uncompressed by the browser. That should help a bit.
Maybe something like this.
Or better still, in IIS itself like this.
considering that you're importing the jquery UI library, jquery, the microsoft ajax framework, some validation framework etc.. its not too bad..
You can try minify the files to save space. Here YUI Compressor
If you are using well-known and popular libraries (like jquery) you can use externally hosted files from a cdn (content delivery network), which are more than likely already in the browser cache (and therefore won't need to be downloaded again): google list of libs and jquery ref
Minify it :http://jscompress.com/
I would also suggest refactor it (rewrite it so there is less memory used).
Telerik Extensions For ASP.NET MVC
How about this approach?
MvcContrib: an Outer Curve Foundation project
MvcContrib.IncludeHandling is same approach.
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.