PageSpeed and Yslow suggest that to combine javascripts file to reduce HTTPRequest. But this is becuase (I think) pre ie8 browser has no more than 2 serverhost connection.
But nowaday, browser has 6 serverhost connections, which means it has download javascripts in parrallel. So let say we have 1MB of javascript, should we break it down into 6 different files in similar size to obtain max download speed? Please let me know.
Micahel.S
No, because each HTTP request involves overhead (less if pipelining is used)
The answer to your question is no. However, assuming you are able to serve your content in a completely isolated environment where only IE8 is used (like company intranet), then the answer to your question becomes: no.
Since you aren't designing for IE6-7 I assume you are in an isolated environment (otherwise you are making a poor designing decision). In this environment, yes you might see small benefits from breaking down JavaScript files, but I recommend against it.
Why? Since you are optimizing for speed, I assume you are putting JavaScript at the bottom of the body tag in your HTML document, in order to prevent JS from blocking download of DOM. This is a fundamental practice to make the page appear to be loading faster. However, by placing the content in the bottom of the body, your question becomes moot. Since the DOM is no longer being blocked by the script tags, whatever speed benefits you could achieve by using parallel downloading would be lost on the user because they see the page load before the browser even requests the JavaScript files.
tl;dr: There is no practical speed advantage to break JS into multiple files for parallel downloading.
Splitting the files won't make too much of a difference really. If you want to see performance gains in terms of download times for your Production environment what I always do is use YUI Compressor (http://developer.yahoo.com/yui/compressor/) to get my JS file size down as small as possible then serve a gzipped version of the js to browsers that support it.
In a development environment you shouldn't be too worried about it though. Just split them logically based on their purpose so they're easier to work on then bring them all together into one file once you're ready and optimize it for production.
Most browsers will cache your JavaScript files anyway, so after the first page load, it won't matter.
But, you should split your JavaScript logically and in a way that would most help you in development, since browsers vary in the number of simultaneous connections they allow.
For speed, you can obfuscate your code (via a minimization routine) and serve it in a way no human would have the patience to read.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I would like to know if it is advisable to embed (inline) all CSS and JavaScript that are required by a webpage, into and tags instead of letting the browser download these files. Is such a practice advisable?
My "application" is a SPA and I have managed to compile everything, even images and font-icons (as base64) into a single index.html, but I am not sure if this is a common practice.
Thanks in advance.
You are ignoring some crucial things:
Browser can fetch specific resources in parallel, thus reducing the time of load compared to the "pack altogether" approach.
Browser can apply different caching policies for a different type of resources, which also can be used for some clever time and/or badnwidth reducing tuning.
People can get some useful data even if not all resources are loaded.
Not all functionality in SPA is heavily used, so sometimes it makes sense to load some entities lazily, on demand.
This is a very basic and simplified overview, there's a lot of thing to consider here. Moreover, budling to a bigger chuncks is actually something used in practice. Say, pretty often all js resources are bundled. But definitely trying to get rid of any additional http request will make your architecture less flexible, less cacheable and so on. So, it's overkill.
Best practice would be to split each resources(scripts, CSS, images, etc.) into separate files. Which will allow browser to download and cache each resource for future reuse(even for other pages). But browsers have limit into six(on time of writing) parallel connections per one origin. That why a lot of external resources on page cause bad page loading performance and bad waterfall.
There are a lot of techniques to improve performance such as: bundling, domain sharding, image sprites etc. Also for some critical resources you can use inline technique. It allows browsers to use this resources instantly without additional requests. For example, you can embed all resources(image, CSS, scripts) that are required for loading indicator and browser will render it without additional requests.
For best development style do not embed resources and use separate files. In case you care about performance you should investigate waterfall of your page(e.g. here or network tab in developer tool of any browser) and use some techniques to improve it. If you are interested in this field I recommend you to read books below:
High Performance Web Sites by Steve Souders
Even Faster Web Sites by Steve Souders
High Performance Browser Networking by Ilya Grigorik
Note that this techniques are relevant only for HTTP 1.1. For HTTP 2.0 it will be only harmful because new version is designed to improve performance.
No, always avoid inline-styling and scripting to reduce the page load of the html file. Also, separating your html, your css and your js keeps your coding clean, semantic and reusable for other external pages or applications that may require a common css property or script.
It's all about where in the pipeline you need the CSS as I see it.
inline css
Pros: Great for quick fixes/prototyping and simple tests without having to swap back and forth between the .css document and the actual HTML file.
Pros: Many email clients do NOT allow the use of external .css referencing because of possible spam/abuse. Embedding might help.
Cons: Fills up HTML space/takes bandwidth, not resuable accross pages - not even IFRAMES.
embedded css
Pros: Same as above regarding prototype, but easier to cut out of the final prototype and put into an external file when templates are done.
Cons: Some email clients do not allow styles in the [head] as the head-tags are removed by most webmail clients.
external css
Pros: Easy to maintain and reuse across websites with more than 1 page.
Pros: Cacheable = less bandwidth = faster page rendering after second page load
Pros: External files including .css can be hosted on CDN's and thereby making less requests the the firewall/webserver hosting the HTML pages (if on different hosts).
Pros: Compilable, you could automatically remove all of the unused space from the final build, just as jQuery has a developer version and a compressed version = faster download = faster user experience + less bandwidth use = faster internet! (we like!!!)
Cons: Normally removed from HTML mails = messy HTML layout.
Cons: Makes an extra HTTP request per file = more resources used in the Firewalls/routers.
Source/Reference : here
Keeping all the HTML, CSS, and JavaScript code in one file can make it difficult to work with. Stylesheet and JavaScript files must contain the and tags respectively, because they are HTML snippets and not pure .css or .js files.
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.
When you're hard at work on your markup, sometimes it can be tempting to take the easy route and sneak in a bit of styling.
I'm going to make this text red so that it really stands out and makes people take notice!
Sure -- it looks harmless enough. However, this points to an error in your coding practices.
Instead, finish your markup, and then reference that P tag from your external stylesheet.
someElement > p { color: red;}
Remember -- the primary goal is to make the page load as quickly as possible for the user. When loading a script, the browser can't continue on until the entire file has been loaded. Thus, the user will have to wait longer before noticing any progress.
If you have JS files whose only purpose is to add functionality -- for example, after a button is clicked -- go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice.
I'm new to JavaScript.
How should I split my functions across external scripts? What is considered good practice? should all my functions be crammed into one external .js file or should I group like functions together?
I would guess more files mean more HTTP requests to obtain the script and that could slow down performance? However more files keep things organized: for example, onload.js initializes things on load, data.js retrieves data from the server, ui.js refer to UI handlers...
What's the pros advice on this?
Thanks!
As Pointy mentioned, you should try a tool. Try Grunt of Brunch, both are meant to help you in the build process, and you can configure them to combine all your files when you are ready for prod (also, minify, etc), while keeping separate files when you are developing.
When releasing a product, you generally want as little HTTP requests as possible to load a page (Hence image sprites, for example)
So I'd suggest concatenating your .js's for release, but keeping them separated in a way that works well for you, during development.
Keep in mind that if you "use strict", concatenating scripts might be a source of errors.
(more info on js strict mode here)
It depends on the size, count of your scripts and how many of them you use at any time.
Many performance good practices claim (and there's good logic in this) that it's good to inline your JavaScript if it's small enough. This leads to lower count of HTTP requests but it also prevents the browser from caching the JavaScript so you should be very careful. That's why there're a practices even to inline your images (using base64 encoding) in some special cases (for example look at Bing.com, all their JavaScript is inline).
If you have a lot of JavaScript files and you're using just a little part of them at any time (not only as count but as size) you can load them asynchronously (for example using require.js). But this will require a lot of changes in your application design if you haven't considered it at the beginning (and also make your application complexity bigger).
There are practices even to cache your CSS/JavaScript into the localStorage. For further information you can read the Web Performance Daybook
So let's make something like a short retrospection.
If you have your JavaScript inline this will reduce the first load of the page. The inline JavaScript won't be cached by the browser so every next load of your page will be slower that if you have used external files.
If you are using different external files make sure that you're using all of them or at least big part of them because you can have redundant HTTP requests for files which actually are unnecessary loaded. This will lead to better organization of your code but probably greater load time (still don't forget the browser cache which will help you).
To put everything in at single file will reduce your HTTP requests but you'll have one big file which will block your page loading (if you're using synchronous loading of the JS file) until the file have been loaded completely. In such case I can recommend you to put this big file in the end of the body.
For performance tracking you can use tools like YSlow.
When I think about good practice, then I think of MVC patterns. One might argue if this is the way to go in development, but many people use it to structure what the want to achieve. Usually it is not advisable to use MVC at all if the project is just too small - just like creating a full C++ windows app if you just needed a simple C program with a for loop.
In any case, MVC or MV* in javascript will help you structure your code to the extent that all the actions are part of the controllers, while object properties are just stored in the model. The views then are just for showing purposes and are rendered for the user via special requests or rendinering engines. When I stared using MV*, I stared with BackboneJS and the Guide "Developing BackboneJS Applications" from Addy Osmani. Of course there are a multitude of other frameworks that you can use to structure your code. They can be found on the TodoMVC website.
What you can also do is derive your own structure from their apps and then use the directory structure for your development (but without the MV* framework).
I do not agree to your concern that using such a structure lead to more files, which mean more HTTP requests. Of course this is true during development, BUT remember, the user should get a performance enhanced (i.e. compiled) and minified version as a script. Therefore even if you are developing in such an organized way, it makes more sense to minify/uglify and compile your scripts with closure compiler from Google.
I am curious as to why the Facebook developers have chosen to not combine their scripts and stylesheets into single files. Instead they are loaded on demand via their CDN.
Facebook is obviously a very complex application and I can understand how such modularity might make Facebook easier to maintain, but wouldn't the usual optimisation advice still apply (especially given its high level of usage)?
Or, does the fact that they are using a CDN avoid the usual performance impact of having lots of small scripts / styles?
In a word BigPipe. They divide the page up into 'pagelets' each is processed separately on their servers and sent to the browser in parallel. Essentially almost everything (CSS, JS, images, content) is lazy loaded, thus it comes down in a bunch of small files.
They might be running into the case where the savings of being able to serve different combinations of JS files to the browser at different times (for different pages or different application configurations for different users) represents a larger savings than the reduced HTTP request overhead of combining all of the files into one.
If a browser is only ever executing a small percent of the total JS code base at any given time, then this would make sense. Because they have so many different users and different parts of different applications running in different configurations for those users, it is arguable that this is the case.
Second, those files only need to be downloaded once, then the browser won't ask for them again until they have changed or the cache has expired, so only the first visit really benefits from the all-in-one style. And yes having and advanced CDN with many edge locations around the world definitely helps.
Maybe they think it's more likely that you visit Facebook more often than you clear your browser cache.
Ignoring download times, what's the performance impact of making the browser interpret several separate small files as opposed to one big one. In particular, could it make a significant difference to page rendering speed in ie6 and 7?
Browsers typically limit themselves to a certain number of simultaneous requests. This number is dependent on how "server friendly" they are.
How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?
So, depending on the number of artifacts the browser has to load, it may have to wait for others to complete first. Artifacts include everything the browser has to go back to the server for: images, javascript, css, flash, etc. Even the favicon if you have one.
That aside, rendering speed is normally going to boil down to how the pages are structured. ie. how many calculations you depend on the browser to make (% width vs fixed width).
It has to make more round-trip HTTP requests. It may or may not have significant consequences.
Where,
Apart from download times , if you too have many javascript and css files
Each request is as an extra http call from client to server.
If the page load is one of the main criteria you should definetly think about it
read this doc also
http://developer.yahoo.com/performance/rules.html
I work for a gov't organization with a large scale enterprise intranet and when we had around 25+ JS files and 10+ CSS files loading on our intranet portal we did notice a dramatic lag in page load time in IE6 and 7. Newer browsers have faster routines for loading and executing JavaScript. I used YUI Compressor to minify everything including CSS.
If you include minification in along with combining files, then dead code often gets removed (depending on the minifier) and some code can be optimized (see YUI Compressor: What are micro optimizations? and Which javascript minification library produces better results?).
I've asked this question a bunch of times when I first started out with web development.
If you have under 10 javascripts and 10 css files (css not so important in my opinion), then I don't think there is much use minifying and compressing. However, if you are dealing with a bunch of javascript files (greater than 10), then YES, it's gonna make a difference.
What you may experience is, even after compressing and minifying and combining your scripts, you may still experience slow-ness. That's when HTML caching plays a huge role in website optimizations, at least that's what I experienced in my web application. Try looking into Memcached and use it to cache your html files. This technique speeds up your web application a WHOLE LOT!!!
I am assuming your question is related to web optimization and high performance websites.
Just my 2 cents.
I'm making an AIR application (so the download time doesn't have a huge impact). Does combining and minifing all the JavaScript files affect the performance? How would obfuscating affect the performance?
Minifying improves performance for your page overall by decreasing the load time (even if only slightly).
Neither minifying nor obfuscating alter the execution time by any perceivable amount for the vast majority of JavaScript code out there.
I do recommend minifying for those reasons and more. Minifying multiple scripts together (like jQuery and its plugins) can yield even greater savings.
As pointed out, on constrained devices and/or with very large codebases minifying could yield a noticeable result.
Minification
Minification does improve performance for two reasons:
Reduced file-size (because it removes comments and unnecessary white spaces), so your script loads faster. Even if it is embedded into the <head>.
It is parsed faster, since comments and white spaces don't have to be explicitly ignored (since they're not there).
Combining
I've written quite a few HTML/JavaScript AIR applications, and from personal experience, combining files won't make a difference. In fact, it's good practice to separate the script based on certain criteria (classes, global functions, SQL functions, etc.). It helps keep them organised when the project becomes too big.
Obfuscation
Obfuscating is usually a combination of minification and renaming variables. It involves using eval to blow up the code again. This reduces performance for obvious reasons, but it depends on the size of your code.
I'd suggest running tests to understand this best for your specific situation.
Everyone here already talked about minifying, but nobody talked about the second part of your question - combining. This will definitely improve performance, probably even more than minifying.
Multiple files require multiple HTTP requests, so when you put them all into one file, only one request is needed. This is important for two reasons:
each individual HTTP request may take longer to load for various routing reasons, and one file will potentially delay your whole application.
browsers and other clients have a maximum limit of files they are allowed to download concurrently from a single domain. Depending on the number of files in your application, this may mean the client queuing them up, thus making the load even longer.
Also, besides minifying and combining, you have to absolutely make sure you have some sort of server-side compression enabled. This can save you 90% or even more in the amount of bytes transferred, depending on the files.
You can read more about compression (gzip, deflate) in How to make your site lightning fast by compressing (deflate/gzip) your HTML, JavaScript, CSS, XML, etc. in Apache.
Minification does not improve the speed at which JavaScript executes at runtime, which I believe it what you're really interested in. In fact, if you use Packer's Base64 compression, it's actually slower on initial load.
Minification will reduce the size of the JavaScript though, making your application's download size smaller.
Minifying strips out all comments, superfluous white space and shortens variable names. It thus reduces download time for your JavaScript files as they are (usually) a lot smaller in filesize. So, yes it does improve performance.
The obfuscation shouldn't adversely affect performance.
The article Best Practices for Speeding Up Your Web Site talks about minifying.
I'd like to post this as a separate answer as it somewhat contrasts the accepted one:
Yes, it does make a performance difference as it reduces parsing time - and that's often the critical thing. For me, it was even just simply linear in the size and I could get it from 12 seconds to 4 seconds parse time by minifying from 3 MB to 1 MB.
It's not a big application either. It just has a couple of reasonable dependencies.
So the moral of the story here is: Yes, minifying is important for performance - and not because of bandwidth, but because of parsing.
According to this page:
Minification in JavaScript is the process of removing all characters that are not necessary from the JavaScript source code. That is why it is called “minification” – because all of the data that is not necessary to the functioning of the JavaScript is removed from the source code, and therefore the JavaScript is “minimized”. Even though these characters are removed from the JavaScript source code, the functionality of the JavaScript code does not change at all.
So, your JavaScript code will behave exactly the same even after it goes through the minification process. Code that has gone through the minification process is also known as “minified” code
What are the benefits and advantages of JavaScript minification
The main purpose of JavaScript minification is to speed up the downloading or transfer of the JavaScript code from the server hosting the website’s JavaScript. The reason that minification makes downloads go faster is because it reduces the amount of data (in the minified JavaScript file) that needs to be downloaded. Less data means that the user’s browser spends less time processing that data, which is why time is saved. So, we can say that minification is performed on JavaScript source code because it is essentially a performance enhancement – and it allows websites that use minified JavaScript to load faster.