External or Inline JavaScript? - Page Load Time - javascript

Would a page load faster if I keep all my JavaScript in a separate file say MyCode.js and include that file rather than have the JavaScript included in the html file?
Or does it not really matter?

It very rarely matters for speed purposes unless you're Google. However, for readability and maintainability, it's much better to keep your JavaScript in external files.
If you put your <script> tags at the end of the page (just before the closing <body> tag) the JavaScript won't block loading of the page.

There are benefits for both inline and included script files.
Inline scripts get loaded with the HTML therefore only one HTTP request is required to download both this saves time, the resulting HTML file will be bigger but you do not waste time with the handshake and headers.
Included scripts get loaded as a separate HTTP request and therefore there is this overhead, however, included scripts get cached by the browser which means subsequent pages do not need to request this resource from the server again.
As a rule, include inline scripts wherever those scripts directly relate to the content of the page that is being requested, you will save HTTP requests for the page and you do not need to cache the scripts separately. For site wide scripts, always include these as separate script files, these will get downloaded once the first time they are needed and then a cached copy will be used for subsequent pages.

If you've got plenty of scripts, there might be some to be saved by keeping js in external files as it allows the browser to do a better job of caching your script files. Same goes for CSS.
But generally, meh. The obvious advantage of externalising is maintainability.

Depending on JS code size. If You have huge JS code part then putting everything separately has few pluses:
You can split different file types among different domain names which can increase page load time - while most of browsers limit to 4 concurrent connections to the same domain.
It is easier to maintain

Related

Is it better to split JavaScript into multiple files, or have it all in one file?

Assume a website running on a Linux server. There are three pages. One page has an AJAX call, one has a JavaScript-generated calendar, and the third has a lightbox image gallery. They also share some common JavaScript functions.
There are two ways I've handled this kind of setup before. Method 1: create four .js files. One with the common functions (loaded on every page), and three more with each distinct page function. Each page loads two scripts: the common script, and the specific script for that page's content. The page makes one extra HTTP request, but doesn't load any extraneous script.
Method 2: Put everything in a single .js file, and each page loads that one file. Only one HTTP request, but each loads a lot of extraneous JavaScript (for example, the Calendar page will also be loading the script for the Gallery page AND the AJAX call page).
Assuming that proper function naming etc. is not an issue, so we don't need to be concerned about function name overlapping etc, which scenario is best for site load time and overall performance? An extra HTTP request per page, or lots of extraneous JavaScript per page?
It depends on the size of your Javascript and the data connection of the user, as well as the (non-)use of technologies such as HTTP2.
In general the answer is that combining separate Javascript files into a single file per page is better for performance. There's nothing to say you couldn't do this separately for each of your pages, meaning you'd have a single Javascript file with the page-specific functions, as well as the common functions you've described. You can do that manually, or use a tool like gulp to perform the task automatically.
I would serve them in one file as one HTTP request is preferable even to loading lots of JS. If it is a huge JS file, consider minification.
I would do one file, and make sure your server response headers allow client-side caching. Then there is only one HTTP request for the JS file, even if they visit all the pages on your site.

Increase Page Speed and YSlow Grade

I've cheked my MyBB forum in gtmetrix.com and gave this performance report:
http://gtmetrix.com/reports/www.forum.joorchin.net/TdxokjnO
Now I have many question to increase the Page Speed and YSlow Grade.
How can I defer the parsing of javaScripts?
How can I remove query string from static resources?
How can I cache the .swf and .js files? (Leverage browser caching)
How can I increase the Recommendations score in YSlow tab? (Medium and High PRIORITY)?
1- I think by defering parsing the javascript, they mean by putting all javascript at the end, or loading javascript asynchronously. Basically when a browser sees a script tags, it stops rendering the page until the javascript is interpreted in the script tag. Thats why its suggested to place all javascript at the end of a html page. you may or may need to change your code/js to handle this.
3 For caching .swf / .js files , if you are using Apache enable the expires module and set the revelant expires headers for the same
Rather than complicate your JS loading just merge them into one JS file and minify it (if possible). Do the same thing with your CSS so you are only requesting one JS file and one CSS file per page load.
Then use Apache to control the cache headers for all resource types by adding these Apache settings to either .htaccess or http.conf.
If you have an image heavy page design you may also look into using image sprites to reduce the number of images being retrieved from the server. Also make sure your images are compressed (i.e. smaller KB size) using a good web image processing tool like Fireworks, Photoshop, etc.
The majority of performance issues are related to the number of HTTP requests being made. You are right to ask about caching, but the initial page load (ie. before the cache is filled) is also important as it's the first impression a visitor will get of your site.

How to reduce the page load time?

I have a web page I run locally on a WebKit mobile browser (not on a web server) which has around 27 MB of JavaScript files, YES 27 MB of JavaScript files. It is because I have custom JSON objects and arrays hard-coded inside my .js file.
I have split the complete JS contain into 27 small .js files of around 1 MB.
The problem is that when I includes these .js files inside my header, the page load time increases very much.
I'd like to know how can I reduce the page load time in such a case where the js files are required.
1) Is there a way wherein we can inject the .js files inside the HTML after the page loads for the first time? (because the JavaScript content comes into picture only after a link is clicked on the page)
2) What would be an optimium solution to includes such a large JavaScript content inside a web page? I have minified my all js files to reduce the file size as much as possible!
Thanks in advance.
UPDATE 1:
The page runs locally and no WEB SERVER is involved. Finally, it would run inside a mobile browser, and so that's how all the problem arised i.e. the load timing is very high in mobile browser, so want to reduce the initial load time.
(Note: Most of the below was written before you'd bothered to tell us you were running an HTML file locally in a mobile browser without using a web server. Much of it still applies, some of it doesn't, but I've left it for others actually doing web pages.)
1) Is there a way wherein we can inject the .js files inside the HTML after the page loads for the first time?
Yes, it's actually really easy (live example: run / edit):
var script = document.createElement('script');
script.src = "path/to/the/file.js";
document.body.appendChild(script);
Note that the script will load asynchronously (you can't just assume it's loaded after the appendChild call).
But if your goal is just to have the page showing while the 27MB file downloads, you can just put your script tag at the end of your page, just before the closing </body> tag. Update: If you're running a local HTML file, not a web page, I'd think this is all you'd need: A single script tag at the end of the page loading your 27MB .js file.
2) What would be an optimium solution to includes such a large JavaScript content inside a web page?
Ideally, reduce the size if at all possible. If you can demand-load assets as you need them (either using the technique above or ajax), do that instead. Update: If you're running a local file, not a web page, you basically can't do ajax reliably. But you can demand-load what you need, when you need it, via adding script elements as per the above.
Regarding your 27 1MB .js files: If you hardcode the script tags for them, it's much better to do one 27MB file than 27 1MB files. Minimizing HTTP requests to your server (ideally at most one .js file and one .css file) is one of the key ways to improve page load time. In your case, though, you've said various parts aren't needed until various things are clicked, so you'll probably end up with a main file (which will hopefully be a lot smaller than 27MB), and then a bunch of other things you demand load (as per the above) as necessary.
Other things you can do:
Minify, compress, or "compile" your .js files (this means you'll have separate "source" and "production" files, since typically this is a one-way process that removes comments and such)
Ensure that your server is serving .js files with gzip compression (for instance, with Apache you'd use mod_deflate); you can test that it's working with various tools
Also very much worth a read: Best Practices for Speeding Up your Website, which makes the points above and a whole bunch more.
At 27MB it's always going to be slow as you're going to run into the memory limits on the device.
Most mobiles don't have a lot of RAM and once you load and parse the JSON it's going to be using more the 27MB
Minification will help you but gzip won't as the browser still has to decompress it)
If you're just rendering HTML in response to user actions, why don't you create HTML fragments instead of JSON and fetch these and insert them into the DOM when someone clicks on the link?
You have to combine again that *.js files into one. That will reduce the server requests that cost in time !
Compress your JavaScript content with that tool : http://www.refresh-sf.com/yui/ or that http://closure-compiler.appspot.com/home
Also you have to put that files at the page footer, in order to allow the page to be rendered while you download the js files into the client browser.
Another thing that can help is the long time caching of the file. This will allow your JavaScript to be "saved" into client web browser cache and next time is not important to re-downloaded.
Finally I am not 100% sure is that help but try lazy JavaScript loading.
Edit for Lazy Laod
<script type="text/javascript">
(
function()
{
var sc = document.createElement('script');
sc.type = 'text/javascript';
sc.async = true;
sc.src = 'http://www.url-to-your-javascript.file/my-javascript.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(sc,s);
}
)();
</script>
Another helpful source
http://gtmetrix.com/dashboard.html
Tests your web site speed. This will help you find your way on speed optimization about your web site :)
I would load the data after page load with ajax. That is after you loaded the page, you make an asyncronous request for the 27MB of data. This allows you also to eventually add a load animation while the data is transferred. You can have a look at jquery to implement this.
As a best practice, you should always load javascript in bottom oh html file. Put css at top, and js at bottom will greatly help.
27MB is too large. Why are you using hard code in js. you can use ajax. Take help from an expert, may be he can minimize your js
I finally solved over this problem of mine by creating a native application for the mobile device rather than using the hybrid (HTML5) technology i.e. I moved the 27 MB JS files which were containing the actual app data to an sqlite file and used it directly in my Android app.

Can JavaScript be cached if it is in the body tag of an HTML page?

I am reading this How to make HTML rendering fast it says that scripts in the HEAD tag can be cached.
Can JavaScript in the BODY tag be cached? If not, why does YUI recommend putting scripts in the body tag?
JavaScript will be cached (and reused between pages) if it is in an external file and the cache control headers say it should be cached.
It may be cached if it is embedded in the page itself (i.e. between <script> and </script> instead of at the end of src="..."), but only if the entire page is cached and it will not be reusable between pages.
It makes no difference, to caching, if the <script src="..."></script> is in the head or body.
The code will be cached if you cache the entire HTML page, not otherwise. HTML pages are usually dynamic these days (generated by scripts and CGIs) and therefore not possible to cache without sacrificing functionality. Therefore you usually want to place JS code in external files which then can be cached by setting HTTP cache headers for the JS file.
The answer, for the most part, is that you cannot cache JavaScript which is inlined into the HTML code (in the HEAD section or otherwise). To make it cacheable you need to put it in an external file, but then the browser will need to do an extra HTTP request to get the JavaScript the first time.
Mate, I think you might have misunderstood what Rich said.
He said put the JavaScript into an external file and link it from the head.
This is in contrast to placing the JavaScript into a script tag in the body of the page.
It would be reasonable to put JavaScript into a script tag in the page body if it is used only on that page. In fact, if its used only one that page, it would not be an optimisation to place it into an external file. The additional GET request for the JS file will be almost simultaneous on Firefox, Opera, Safari but not on IE6. The reason is that IE6 has only a few (2) threads to use for fetching files, whereas Firefox has up to 16. That is why having a separate file for page-specific code would be a step backwards because it might actually slow down the page load.
If however, you have a common JavaScript file that you want to use on many pages then you should definitely place it in an external file and link it from the head, because it will be cached the first time any of those pages are loaded, and it will not need to be fetched again when any of the other pages use it. The bigger the file, the bigger the advantage to caching it.
I think that was the point he was making. Does that help?

Use cache file or one more HTTP Request?

on all the "speed up your website" sites and books they always tell us to minimize HTTP requests at all costs. This is fine and nice but what if that means that on every page you have to reload 120kb again and again and again because the user cache is empty?
If i use 5 js files on every page of my website, wouldnt it be better to put them in one file and load this file on every page instead of putting them together with all other variable files in one big file and save one HTTP request. From which point or filesize on is it ok "cache" a file and have another HTTP request?
I give you an example of 3 pages when i use only one HTTP request for one minifed JS file per page:
jquery, jquery ui, thickbox, lavalamp menu => together minified in one file = 300kb
jquery, jquery ui, cycle plugin => together minified in one file => 200kb
jquery, jquery ui, galleria plugin => together minified in one file => 250kb
And now the other possibility with always 2 HTTP requests: One File consisting of jquery and jquery ui => 150kb, lets call it "jui.js" for now
jui.js, thickbox, lavalamp = again 300kb in the beginning, BUT now jui.js is cached for the other 2 pages
(jui.js is cached now so not loaded), only cycle plugin => only 50kb to load but one more HTTP request as i load jui.js and the cycle plugin seperately.
(jui.js is already cached), only load galleria plugin => only 100kb more to load but again 2 HTTP requests where one request is already cached
So at which point or Kb size is it ok to have another HTTP request on a normal "responsive" web server?
Does anybody have any best practices or is it just "Minimize HTTP requests at all costs!"?
(I hope i made myself clear :) And i will vote up people as soon as i have some points!)
EDIT:
It is basicly a simpler question:
How long does a extra HTTP roundtrip for a cached js file need? If the http request is slower than the time i would need to download the extra non cached parts on every page, then i would put everything in 1 big file on every page(1 different big file on every page).
If the HTTP request for a cached js file is nearly nothing, then i would split the parts that every page needs in an extra js file(minifed of course) and include the dynamic parts of every page in differend(again minified) js files.
So if on most pages i need a 100kb extra(the dynamic part), how do i test the time for a cached HTTP request? Are there any numbers, did anybody test something like this already?
Thanks for the great answers already!
This is big complex subject. They write whole books on this subject ;)
For resources (javascript, css etc) it is sometimes better to download them individually. The browser will download them in parallel. if page a needs resources x y z but page b only needs x and z, separating them out is a good thing. Other times a resource that is needed on every page might be better downloaded all at once. It depends.
But with javascript, the browser downloads the JS first before it renders the page (if the script tag is in the head section) so you would see better performance if you add a defer attribute, or include at the bottom of the page, and trigger your javascript with a body=onload.
Remember too you can set caching headers on resources so the browser will cache them in memory or disk. This makes a huge difference in many cases.
There are really no hard and fast rules, just some guidelines. Your best bet is to test! what works better over dialup doesn't work as well over broadband.
Fiddler is a nice program that will show you your loading times if you are on a modem for instance.
in short, there is no rule of thumb here. Depending on your webserver settings you may want to try optimizing by merging files to one larger file... I know apache could be configured to use same connection to stream several files. Best thing to do is use a benchmarking tool such as apache AB to simply test your changes.
As for jquery stuff though, you may include your scripts from a publicly located domain such as google to 1) avoid connections 2) many people have them cached in browser already.
ie: http://code.google.com/p/jqueryjs/
You'll really have to do your own analysis based on your own traffic. Initial load times matter too, so if users are landing on a page with a single JS, you may want to split that out. However, if users end up clicking around on your site a bit, the net benefit to loading it all at once is obvious.
That said, my users land on "content" which needs more scripts, and so I usually lean towards minimizing what I can on the assumption that users will click around.
I'll leave the argument about linking to google's copy of your scripts to a link to a previous discussion:
Should I link to Google API's cloud for JS libraries?
I think how you handle this situation heavily depends on the type of traffic your site gets. If it is a site where people are only hitting a few (less than 3) pages and leaving then you can split up files more liberally with the assumption that you are giving users only the minimum for what they need. However, if your site gets users who are viewing a lot of pages then just bundle most of it up and ship it over once.
Also, take a look at where the javascript is being used before putting it into the javascript package. If it is only used a page or two that aren't frequently visited then you can make it a separate file.
In practice, since you are gzipping your scripts when they are sent out (your doing that right?) then its often faster to just include scripts since you avoid the extra round-trip-time. Like Byron mentioned, downloading javascript blocks everything else from being loaded (unless its done asynchronously) so you want to do your best to minimize that time.
Start playing around with the Net tab in Firebug to see how performance is affected.

Categories

Resources