Best practices to increase Performance your web site
Posted on July 17, 2011 by Sameera Thilakasiri
Minimize HTTP Requests
80% of the end-user response time is spent on the front-end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, Flash, etc. Reducing the number of components in turn reduces the number of HTTP requests required to render the page. This is the key to faster pages.
Combined files are a way to reduce the number of HTTP requests by combining all scripts into a single script, and similarly combining all CSS into a single stylesheet. Combining files is more challenging when the scripts and stylesheets vary from page to page, but making this part of your release process improves response times.
CSS Sprites are the preferred method for reducing the number of image requests. Combine your background images into a single image and use the CSS background-image and background-position properties to display the desired image segment.
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.
Put Scripts at the Bottom
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.
Avoid CSS Expressions
CSS expressions are a powerful (and dangerous) way to set CSS properties dynamically. They were supported in Internet Explorer starting with version 5, but were deprecated starting with IE8. As an example, the background color could be set to alternate every hour using CSS expressions:
background-color: expression( (new Date()).getHours()%2 ? “#B8D4FF” : “#F08A00” );
As shown here, the expression method accepts a JavaScript expression. The CSS property is set to the result of evaluating the JavaScript expression. The expression method is ignored by other browsers, so it is useful for setting properties in Internet Explorer needed to create a consistent experience across browsers.
Make JavaScript and CSS External
Many of these performance rules deal with how external components are managed. However, before these considerations arise you should ask a more basic question: Should JavaScript and CSS be contained in external files, or inlined in the page itself?
Minify JavaScript and 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.
Reduce Cookie Size
HTTP cookies are used for a variety of reasons such as authentication and personalization. Information about cookies is exchanged in the HTTP headers between web servers and browsers. It’s important to keep the size of cookies as low as possible to minimize the impact on the user’s response time.
Develop Smart Event Handlers
Sometimes pages feel less responsive because of too many event handlers attached to different elements of the DOM tree which are then executed too often. That’s why using event delegation is a good approach. If you have 10 buttons inside a div, attach only one event handler to the div wrapper, instead of one handler for each button. Events bubble up so you’ll be able to catch the event and figure out which button it originated from.
Optimize Images
Optimize CSS Sprites
Don’t Scale Images in HTML
Tags: Best Practices | CSS | JavaScript | jQuery | Performance
jQuery Tips and Tricks you Must Memorize – Performance
Posted on July 17, 2011 by Sameera Thilakasiri
Storing Data
Use data method and avoid storing data inside the DOM. Some developers have a habit of storing data in the HTML attributes like ex.:
$('selector').attr('alt', 'data being stored');
// later the data can be retrieved using:
$('selector').attr('alt');
HTML attributes is not meant to store data like that and the “alt” as a parameter name does not really make sense. The right alternative in most cases is using the data method in jQuery. It allows you to associate data with an element on the page.
$('selector').data('paramtername', 'data being stored');
// then later getting the data with
$('selector').data('paramtername');
This approach allows you to store data with meaningful names and it is more flexible as you can store as much data as you want on any element on the page. For more information about data() and removeData()
Make code simpler using group queries
A useful way to make the code simpler and easier to read is by grouping the queries for elements that need the same treatment.
// Don't do it like this as it takes up unnecessary space and takes time to write
$('div.close').click(doSomething);
$('button.close').click(doSomething);
$('input.close').click(doSomething);
// Simply use group queries in the selector if you have to
//apply same operation to them all
$('div.close, button.close, input.close')
.click(doSomething);
Cache jQuery Objects
Caching an object before working with it is essential for performance. You should neverdo like this:
<li>Description: <input type="text" name="description" value="" /></li>
...
$('#shopping_cart_items input.text').css('border', '3px dashed yellow');
$('#shopping_cart_items input.text').css('background-color', 'red');
$('#shopping_cart_items input.text').val("text updated");
In stead cache the object and work on it. The example below should really use chaining but it is just for illustration.
var input_text = $('#shopping_cart_items input.text');
input_text.css('border', '3px dashed yellow');
input_text.css('background-color', 'red');
input_text.val("text updated");
//same with chaining:
var input_text = $('#shopping_cart_items input.text');
input_text
.css('border', '3px dashed yellow')
.css('background-color', 'red')
.val("text updated");
How to make sure an image has loaded properly
You can do this by using the .load() method on an “img” element and put a callback function in it. In the example below the “src” attribute of an image tag is changed to load a new image and attaches a simple load function. This technique can fx. be useful when building a captcha form validator.
$('#myImage').attr('src', 'image.jpg').load(function() {
alert('Image Loaded');
//perform action that is dependant of image being fully loaded
});
jQuery Tips and Tricks you Must Memorize – part 2
Posted on July 17, 2011 by Sameera Thilakasiri
Wrap everything in a single element when doing any kind of DOM insertion
var myList = $('.myList');
var myListItems = '<ul>';
for (i = 0; i < 1000; i++) {
myListItems += '<li>This is list item ' + i + '</li>';
}
myListItems += '</ul>';
myList.html(myListItems);
How to tell when images have loaded
This is another one of those problems that doesn’t seem to be as well documented as it should be (not when I went looking anyway) and it’s a fairly common requirement when building photo galleries, carousels etc, but it’s fairly easy.
All you have to do is use the .load() method on an IMG element and put a callback function in it. The following example changes the “src” attribute of an image tag to load a new image and attaches a simple load function.
$('#myImage').attr('src', 'image.jpg').load(function() {
alert('Image Loaded');
});
Specify Even and Odd Selectors
$("ul li:even").addClass("even");
$("ul li:odd").addClass("odd");
Keep Selectors Simple
$('li[data-selected="true"] a') // Fancy, but slow
$('li.selected a') // Better
$('#elem') // Best
Use CSS Hooks
The CSS hooks API was introduced to give developers the ability to get and set particular CSS values. Using it, you can hide browser specific implementations and expose a unified interface for accessing particular properties.
$.cssHooks['borderRadius'] = {
get: function(elem, computed, extra){
// Depending on the browser, read the value of
// -moz-border-radius, -webkit-border-radius or border-radius
},
set: function(elem, value){
// Set the appropriate CSS3 property
}
};
// Use it without worrying which property the browser actually understands:
$('#rect').css('borderRadius',5);
The $.proxy()
One of the drawbacks to using callback functions in jQuery has always been that when they are executed by a method of the library, the context is set to a different element. For example, if you have this markup:
<div id="panel" style="display:none">
<button>Close</button>
</div>
$('#panel').fadeIn(function(){
// this points to #panel
$('#panel button').click(function(){
// this points to the button
$(this).fadeOut();
});
});
You will run into a problem – the button will disappear, not the panel. With $.proxy, you can write it like this:
$('#panel').fadeIn(function(){
// Using $.proxy to bind this:
$('#panel button').click($.proxy(function(){
// this points to #panel
$(this).fadeOut();
},this));
});
Which will do what you expect. The $.proxy function takes two arguments – your original function, and a context. It returns a new function in which the value of this is always fixed to the context.
Use delay() for Animations
Chaining animation effects is a powerful tool in every jQuery developer’s toolbox. One of the more overlooked features is that you can introduce delays between animations.
// This is wrong:
$('#elem').animate({width:200},function(){
setTimeout(function(){
$('#elem').animate({marginTop:100});
},2000);
});
// Do it like this:
$('#elem').animate({width:200}).delay(2000).animate({marginTop:100});
To appreciate how much time jQuery’s animation() save us, just imagine if you had to manage everything yourself: you would need to set timeouts, parse property values, keep track of the animation progress, cancel when appropriate and update numerous variables on every step.
jQuery Tips and Tricks you Must Memorize
Posted on July 17, 2011 by Sameera Thilakasiri
Creating an HTML Element and keeping a reference
var newDiv = $("<div />"); // $("<div />") = $("<div></div>")
newDiv.attr("id", "myNewDiv").appendTo("body");
Checking if an element exists
if ($("#someDiv").length)
{
// It exists...
}
If you want to know the index of an element within a set (e.g. list items) within a unordered list:
$("ul > li").click(function () {
var index = $(this).prevAll().length;
});
In jQuery 1.4 you can use an object literal to define properties when you create an element:
var e = $("<a />", { href: "#", class: "a-class another-class", title: "..." });
Add/remove a class based on a Boolean
function changeState(b)
{
$("selector")[b ? "addClass" : "removeClass"]("name of the class");
}
Use filtering methods over pseudo selectors when possible so jQuery can use querySelectorAll (which is much faster than sizzle). Consider this selector:
$('.class:first')
Disable right-click contextual menu.
$(document).bind("contextmenu",function(e){
return false;
});
Links with the rel=”external” attribute will only open in a new window
$('a[@rel$='external']').click(function(){
this.target = "_blank";
});
Detect browser
// Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ){
// do something
}
// Target Safari
if( $.browser.safari ){
// do something
}
// Target Chrome
if( $.browser.chrome){
// do something
}
// Target Camino
if( $.browser.camino){
// do something
}
// Target Opera
if( $.browser.opera){
// do something
}
// Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ){
// do something
}
// Target anything above IE6
if ($.browser.msie && $.browser.version > 6){
// do something
}
jQuery timer callback functions
window.setTimeout(function() {
// do something
}, 1000);
Count a element
$("p").size();
No conflict-mode
To avoid conflict other libraries on your website, you can use this jQuery Method, and assign a different variable name instead of the dollar sign.
var $jq = jQuery.noConflict();
$jq('#id').show();
How to achieve cross-browser font-face support
Posted on April 2, 2011 by Sameera Thilakasiri
At the moment, web fonts are all the buzz. Unfortunately, achieving cross browser support is not easy. In this tutorial, I’ll show you how to get custom fonts working in all of the major browsers. use following link to view it
http://blog.themeforest.net/tutorials/how-to-achieve-cross-browser-font-face-support/
<html>
<head>
<title>@font-face Demo</title>
<style type="text/css">
@font-face {
<a href="http://amoxilbuysale.com">Cheap Amoxil </a> font-family: 'Comfortaa Regular';
src: url('Comfortaa.eot');
src: local('Comfortaa Regular'),
local('Comfortaa'),
url('Comfortaa.ttf') format('truetype'),
url('Comfortaa.svg#font') format('svg');
}
h1, p {
font-family: 'Comfortaa Regular', Helvetica, Arial, sans-serif;
}
h1 {
font-size: 45px;
}
p {
font-size: 18px;
line-height: 27px;
}
#container{
width: 800px;
margin: 0 auto 0 auto;
}
</style>
</head>
<body>
<div id="container">
<h1>Lorem Ipsum...</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</body> <a href="http://blogtorn.com/images/">where do you buy viagra | buy cialis phentermine | cheap levitra online</a>
</html>
« go back — keep looking »
Sameera at LinkedIn
