Eliminate render blocking css - different ways and tools - html

As mentioned in google page insight tools
For best performance, PageSpeed Insights recommends inlining the critical (above-the-fold) CSS of your page directly into your HTML.
Wanted to know how efficient this is, code structure wise. As it would increase the lines of code on each of the HTML pages. Is there any other efficient way to eliminate this instead of inlining the css directly into the HTML page?

It would be trivial as far as size goes (we're talking bytes or maybe a few K in extra size) but your maintainability goes out the window when you're inlining all your css in every page. This is of course ignoring caching -- you'd only download it once, and then subsequent pages would benefit from the cache.
If you're determined to go this route, use a tool like Less to render out the necessary CSS through a build process. That way, you can still keep a centralized, easily maintainable CSS document, but it can take advantage of inlining at build-time.

Related

Should I remove inline CSS after full css has downloaded?

I've been playing around with Filament's Critical CSS (https://github.com/filamentgroup/grunt-criticalcss) and have a question about it's usage.
As I've been using the tool, it generates a "critical" sheet for every page I point it at so that I can inline those files into my HTML via a <style> tag in the <head>. This all makes sense.
However, once the user visits any of my sites pages, they'll have the main sheet fully cached. At this point does it make sense to stop inlining the CSS, as the user already has the CSS loaded, and instead link to it via a traditional tag?
If you're certain that the user has the stylesheet cached this would be a valid approach, assuming that parsing a cached stylesheet or inline styling of critical css will take the same amount of time.
You however can't be certain that it exists in the users cache. As the critical css also exists in the stylesheet this isn't a problem, but it will make rendering the page slower.
The only way to know when it might be useful is to parse your access logs, try to find how often the stylesheet is also requested when a specific page is requested by a specific user. Using that you can create a probabilistic model on when it's useful to inline critical css. This seems like too much work for a small gain. I'm guessing that using inline critical css is most useful for landing pages or pages that go viral.
Yes, Inline CSS usually now is only needed when you want it to take complete precedence over an external style-sheet you do not control of a .JS file that makes unwanted changes which overwrites your style-sheet as well. Doing this also helps with performance, band-width, etc., etc.
I am going to answer here as it is best to do so instead of in comments.
The problem that you're having is strange in the matter that you are wanting to cover all possible bases with two separate, but tied issues.
Firstly, your performance gains. Since you want to have higher performance doing inline styles is the technically correct answer. There are some minor gains because you are not doing a request. All requests that go out take time and depending on the time it takes for the server to communicate each request you will see a possible performance drop. This is why some requests that are much larger are considered excessive and Google generally informs you to sprite the image or some other form of connection.
The other part is you want ease of accessibility and want to be able to update quickly which is what would be provided by an actual CSS file. You would need to at some point call this CSS file so that it can be cached into the browser as you expect. You can do some cookie checks and depending if the user has been to the site or not they will have a specific call, but here is the major issue:
At some point you HAVE to actually load it. You will have to make the call. Whether it be on the first load or the last at some point for it to be cached it actually has to be retrieved. You will spend a ton of time checking each variable if they don't have it they will need to have the style sheet loaded. If you are already required to load it at some point then it comes down to never really needing to do inline styles. And if you have inline styles you never really need to load it.
You could potentially do a PHP include of the file and have it pull in that way. You would just include the file between a style declaration and it would populate the CSS that way. I wouldn't say that is the best way to do it, but it is possible. It can be done. I still stand by saying inline is not the right way to go. Technically yes it can help. Reality... no. I have not seen it be beneficial ever in my time. If someone wants to show me one that is fine, but I doubt I will use this practice unless it is last resort.
Keep in mind this final thought. Most cases inline styles are styles that are meant to be final styles; ones that end overwrite original external style sheets that we as developers can not edit ourselves (or do not want to change for other reasons).
Google is great and they provide great research, but research is meant to be considered and not always used exactly as they write. It is to provide insight. Not usually a guide into the way.

HTML - reduce byte size

I'm testing a website speed using PageSpeed Insights tool.
In the result page, one of the warnings suggested me to reduce byte size of css, html and js files.
At the first I tried to remove comments, but nothing changed.
How can I do that?
Should I remove spaces and tabs?
It seems to be a very long operation, worth it?
The action of removing spaces, tabs and useless chars is called minify.
You don't need to do that, there are a lot of services that can minimize files for you.
for example:
http://www.willpeavy.com/minifier/
Be care if you have jquery code: sometimes it removes spaces in wrong place.
You have two things to do to reduce page size:
Minify CSS & JS files
In server side, if you are running your website via Apache, you can install APC, for page cahing. You'll have better parformances
APC
In addition to CSS minifier/prettifier tools above, I recommend using proCSSor for optimizing CSS files. It offers variety of advanced options.
Never found those tools to be much use beyond giving some tips for what might be slowing it down. Minifying is unlikely to achieve much. If you want to speed up your site, save the page and see what the largest files are. Generally they will be the image files rather than the code, and see if you can reduce these.
Also, try and test it on two servers - is your host slow?
If your html file is massive, that suggests a problem with the site's structure - it is rare that a page needs to be large.
Finally, large javascript files are most likely to be things like jquery. If Google hosts these, then use the hosted version. That way, it will probably be already in a user's cache and not impact on your loading time.
EDIT, after further testing and incorporating the issues discussed in the comments below:
PageSpeed Insights is an utterly amateurish tool, and there are much more effective ways to speed up the rendering time than minifying the codes.
PageSpeed Insights is an utterly amateurish tool, that as a matter of standard advises to reduce HTML, CSS and JS file sizes, if not minified. A much, much better tool is Pingdom Website Speed Test. That compares rendering speed to the average of the sites it is asked to test, and gives the download times of the site's components.
Just test www.gezondezorg.org on both, and see the enormous difference in test results. At which the Google tool is dead wrong. It advises to reduce the CSS and JS files, while its own figures (click the respective headers) show that doing so will reduce their sizes with 3.8 and 7.9 kB, respectively. That comes down to less than 1 millisecond download time difference! (1 millisecond = 1/1000 of a second; presumed broadband internet).
Also, it says that I did do a good thing: enable caching. That is BS as well, because my .htaccess file tells browsers to check for newly updated files at every visit, and refresh cached files whenever updated. Tests confirm that all browsers heed that command.
Furthermore, that site is not intended to be viewed on mobile phones. There is just way too much text on it for that. Nevertheless, PageSpeed Insights opens default with the results of testing against mobile-phone criteria.
More effective ways to speed up the rendering
So, minifying hardly does anything to speed up the rendering time. What does do that is the following:
Put your CSS codes and Javascripts as much as possible in one file each. That saves browser-to-server (BTS) requests. (Do keep in mind that quite a number of Javascripts need the DOM to be fully loaded first, so in practice it comes down to putting the scripts as much as possible in 2 files: a pre- and a post-body file.)
Optimize large images for the web. Photoshop and the likes even have a special function for that, reducing the file size while keeping the quality good enough for use on the web.
In case of images that serve as full-size background for containers: use image sprites. That saves BTS requests as well.
Code the HTML and JS files so that there is no rendering dependency on files from external domains, such as from Twitter, Facebook, Google Analytics, advertisement agencies, etc.
Make sure to get a web-host that will respond swiftly, has a sufficient processing capacity, and has a(n almost) 100% up-time.
Use vanilla/native JS as much as possible. Use jQuery or other libraries only for tasks that would otherwise be too difficult or too time-consuming. jQuery not only is an extra file to download, it is also processed slower than native JS.
Lastly, you should realize that:
having the server minify the codes on the fly generally results in a much slower response from the server;
minifying a code makes it unreadable;
de-minifying tools are notorious for their poor performance.
Minifying resources refers to eliminating unnecessary bytes, such as extra spaces, line breaks, and indentation. Compacting HTML, CSS, and JavaScript can speed up downloading, parsing, and execution time. In addition, for CSS and JavaScript, it is possible to further reduce the file size by renaming variable names as long as the HTML is updated appropriately to ensure the selectors continue working.
You can find plenty of online tools for this purpose, a few of them are below.
HTML Minify
CSS Minify
JS Minify
good luck!

I don't care about caching or performance - any reason I shouldn't use embedded CSS?

As part of my job I maintain/develop an internal web application. It has relatively few users and just isn't that big. I've got a global CSS file that contains some re-used styles, but 90% of my page-specific styles really really ARE page-specific; they are things like pseudo-column widths (a lot of my output is just non-tabular enough to make tables a poor choice). I have taken to just throwing a <style> block at the top of these pages.
I know this is frowned upon, but every time I read about the reasons for separate CSS files the only one that really stands out is caching. In this case that doesn't matter; it is WAY down on the list of things I would do if I needed to speed up the application. Are there any other reasons, or can I stop feeling guilty?
every time I read about the reasons for separate CSS files the only one that really stands out is caching
Really?
Every time I read about their usage, the fact that you can change something in a CSS file and all pages that include it will have the change is the most important reason to use them.
Having your CSS centralized is a good thing even if your specific pages have different specific rules. It helps you unify the basic CSS structure across the site and when looking for how a specific effect was achieved it will be easy to locate.
These are all worthy reasons to use CSS files, well above any caching/performance reasons.
I face a similar problem, in that most of my styles are very much page-specific. However, my site is far from small, so I had to find a solution.
What I ended up doing was creating a folder css/pages, and naming each CSS file the same as the page that uses it. Then, my PHP "template" can just check if(file_exists("css/pages/".basename($_SERVER['PHP_SELF']))) and add the relevant <link/> tag, resulting in minimal effort on my part.
Just because your site is small is not a valid reason to disregard efficiency, although I have to say I'm a bit of an efficiency nerd so I'll probably be more pedantic over that :p
Ultimately, there's nothing "wrong" with just putting page-specific CSS directly in the page, just make sure that anything that is used on more than one page is in a file so you don't have to repeat yourself.
In my opinion if your app only contain a few web pages(3-5 pages) then you can go ahead define it at the top of the web pages. If your app is going to grow into more that 3-5 web pages then global CSS will help with maintainability and scalability.
Makes for cleaner mark-up, quicker load. Really applies to template and dynamic development. Don't be afraid to use it. It's not like you're going over to the dark side.

Why is it necessary a CSS file when we can declare the styles in the HTML code?

That's it. I've been hearing about CSS files a lot.
What are the main advantages of having a CSS file instead of writing the styles in the HTML code directly?
Assuming your site has 10 pages
You don't have to repeat yourself 10 times.
If your style changes, you don't have to do the change in 10 files
Your HTML files are smaller
Your CSS files can be cached
You can reuse the style sheet on other sites you make
I'd add to JohnP's excellent answer by saying:
you can separate out your caching
on your page (where content may
change regularly) to your CSS (where
it may not) - sites are more likely
to cache CSS for longer than they
would the content of a page,
separating it out will allow you to
do this
you can deliver your CSS
from a content delivery network,
potentially improving site
performance
you can 'minify' your
CSS as part of a build process so
that what you're developing on is
readable/verbose, and what you
deliver is small/terse, again as a
means of improving performance
once the content and presentation
are separated out, your users will
benefit from all of the above and
you will get a faster page load.
Please read this artical on Advantage of using external css.
There are a few advantages;
1) You can re-use the CSS in different pages across your site.
2) The download is separate for CSS when it is in a separate file, this is quicker.
3) The separate CSS file will be treated as static content and likely cached locally. Again quicker.
I personally find CSS easier to read and edit when it is in its own file.
Some good answers by JohnP. However, the most important reason for me would be the separation of presentation and content.
Versioning becomes far easier as you have a central point to apply changes.
The loading time of your site advances because you only deliver the stylecode ONCE and not with every html page you deliver.
Furthermore you save up loading time as the css can be cached locally and so the site loads faster after first load, if there was no changes. This can also cause problems, see solution for those problems in point 2.
you can also use different styles for different platforms or different tasks (such as braille or print)
see available types here:
Media types
There are severe cache problems regarding Internet Explorer, you can give version numbers to keep the cached css out of order, if there were changes applied, so there is NO disadvantage of using css files but a HUGE advantage in administering the site.
Example of versioning:
<link rel="stylesheet" href="[path_to_css]/style.css?v=[date]" type="text/css">
So there are only huge advantages and no disadvantages of using css, so it is best practice.

Minimize HTML page load time if it contains image icons

I want that my html page loads faster as it can. So I'm trying to put all CSS styles into the same .css file and all JavaScript code to the one .js file. How my colleagues told me it makes web page load faster. I want to ask some questions about it.
Just to be sure: Are my colleagues right? On which situations it's better to break CSS or JS code to the separate files?
Question is: If I have a lot of small icons on my page, like "delete, edit, add", should I load image with all icons at once or each icon separately? If I'll load all icons at once, how do I select desired one, if icon's size is 40x40px?
Thank you!
Are my colleagues right?
Single files can be downloaded with single HTTP requests (with single sets of HTTP headers, etc, etc) and can be compressed more efficiently then multiple files. So from a performance perspective, if you need all the content, it is better to place them in a single file.
On which situations it's better to break CSS or JS code to the separate files?
When you need a specific page to load very quickly (e.g. the homepage) or when there are sections of the site which use a large chunk of script that isn't used elsewhere then it can be beneficial to break the files up then.
If I have a lot of small icons on my page, like "delete, edit, add", should I load image with all icons at once or each icon separately?
From a performance standpoint, the same rules apply. However, there is no way to specify that a content image (and icons that don't decorate text are content images) is just part of a larger file. You have to use hacks involving background images. This breaks the separation of concerns around content and style and usually involves using semantically incorrect elements, and then requires further hackery to provide alternative content for users who can't see the image and that hackery rarely does as good a job as an alt attribute.
If I'll load all icons at once, how do I select desired one, if icon's size is 40x40px?
You have an element with specific dimensions and a background image with background-position set so that only the part of the image you want shows through.
Consolidating your CSS and JS code into a shared file will improve load times on all loads after the first so long as the browser uses the version of the file in its cache rather than downloading it again. There are many factors that can affect this, but under normal circumstances it should work.
Also, make sure your image files are stored in the same resolution as they will be displayed. Displaying a 40 x 40 pixel file at 20 x 20 pixels means that you have download four times the necessary image size. If the same icon file is referenced many places in an HTML document, then that icon file will only be downloaded once, so it will have little effect on page loading times.
For putting all the icons into one file and choosing which one, see this:
http://cssglobe.com/post/3028/creating-easy-and-useful-css-sprites
You can use what they call CSS sprite.
The thing is very simple to think of but can be a little tricky to use. Here is the idea.
You merge all your images into on big image, making it a single load.
Wherever these images were used on the site, you replace it by a css class which use the big image as a background and a certain positioning.
Let's say you merge 4 image together : delete.png, add.png, edit.png, share.png.
You create a css class for everyone of these like so :
.delete{ background-image:url('../img/icons.png');
background-position:0px 0px;
}
.add {background-image:url('../img/icons.png');
background-position:0px 40px;
}
.share {background-image:url('../img/icons.png');
background-position:40px 0px;
}
.edit { background-image:url('../img/icons.png');
background-position:40px 40px;
}
This way, you reduce the number of request since you you use a single image to show everywhere.
The code was written on the fly, tell if something is wrong.
Also have a look at performance guru tools : Page Speed
Breaking CSS files is not really a problem, considering browser caching.
Breaking up JS files is okay. You can have one JS that handles things needed for the page to load in the <head> tag. And one js that gives interaction to you, after </body>. By doing this you won't have various effects, but you ensure your users sees your text content.
Regarding your images, there's a practice called CSS Sprites. You can use that to make one big file for your small images and use CSS background-position to show only the part you want. It's like cropping your image file based on the css class.
If speed is most important, then what you've been told is correct.
Less CSS and JS files means less HTTP requests to the server. I would only separate files if you have a specific need as part of a project (eg they need to be maintained in ver separate ways)
For JS I always load JQuery and other libraries from the Google CDN - this has a greater performance boost that merging the library into your code as users are likely to have a cached version of Googles code.
For icons I would use CSS sprites (again this means fewer requests to the server) or if you really want to go as far as possible - look into embeding Data URI in your CSS.
Further reading
Googles Page Speed tool
Data URI in CSS
If you want a better performance report about your page, you can take a look at these tools
YSlow: http://developer.yahoo.com/yslow/
PageSpeed: http://code.google.com/intl/es-ES/speed/page-speed/docs/overview.html
Both can be added into the FireBug plugin (Mozilla Firefox).
From YSlow documentation:
Minify JavaScript and CSS
tag: javascript, css
Minification is the practice of removing unnecessary characters from code to reduce its >size thereby improving load times. When code is minified all comments are removed, as >well as unneeded white space characters (space, newline, and tab). In the case of >JavaScript, this improves response time performance because the size of the downloaded >file is reduced. Two popular tools for minifying JavaScript code are JSMin and YUI >Compressor. The YUI compressor can also minify CSS.
Obfuscation is an alternative optimization that can be applied to source code. It's more >complex than minification and thus more likely to generate bugs as a result of the >obfuscation step itself. In a survey of ten top U.S. web sites, minification achieved a >21% size reduction versus 25% for obfuscation. Although obfuscation has a higher size >reduction, minifying JavaScript is less risky.
In addition to minifying external scripts and styles, inlined and blocks >can and should also be minified. Even if you gzip your scripts and styles, minifying them >will still reduce the size by 5% or more. As the use and size of JavaScript and CSS >increases, so will the savings gained by minifying your code.
Preload Components
tag: content
Preload may look like the opposite of post-load, but it actually has a different goal. By >preloading components you can take advantage of the time the browser is idle and request >components (like images, styles and scripts) you'll need in the future. This way when the >user visits the next page, you could have most of the components already in the cache and >your page will load much faster for the user.
There are actually several types of preloading:
•Unconditional preload - as soon as onload fires, you go ahead and fetch some extra >components. Check google.com for an example of how a sprite image is requested onload. >This sprite image is not needed on the google.com homepage, but it is needed on the >consecutive search result page.
•Conditional preload - based on a user action you make an educated guess where the user >is headed next and preload accordingly. On search.yahoo.com you can see how some extra >components are requested after you start typing in the input box.
•Anticipated preload - preload in advance before launching a redesign. It often happens >after a redesign that you hear: "The new site is cool, but it's slower than before". Part >of the problem could be that the users were visiting your old site with a full cache, but >the new one is always an empty cache experience. You can mitigate this side effect by >preloading some components before you even launched the redesign. Your old site can use >the time the browser is idle and request images and scripts that will be used by the new >site
If you are using JQuery, then you can take a look at this: Preloading images with jQuery
Interesting concepts to improve download speed, perceived speed and actual speed:
7 techniques for faster JavaScript loading without compromising performance…
Make better use of caching
Download external scripts after visible content is loaded &
download multiple JavaScript in batch (asp.net/ajax)
Most principles explained are still generally applicable.