Tag Archives: Jquery

Javascript Gurus to follow

10 Jun

As JavaScript developers, we have quite crazy requirements. The playing field is in a state of constant flux and one of the best ways to keep up is interacting with other developers and reading their code. Blogs, such as the one you’re reading are a perfect amalgamation of these two activities.

Today, I’d like to bring your attention to a number of blogs written by pretty well versed developers, focusing on JavaScript development, that you owe yourselves to bookmark.

  • Find his musings on JavaScript at his blog.
  • Inventor of the JavaScript language.
  • Remember to check out his podcast, as well.
  • Tweets at @BrendanEich
  • Find his musings on JavaScript at his blog.
  • Creator of the JS1K competition
  • Tweets at @kuvos
  • Find his musings on JavaScript at his blog.
  • Contributor to the jQuery and Modernizr projects.
  • Creator of so many jQuery plugins that we’re ethically obligated to use the word buttload.
  • Tweets at @cowboy

What Every Frontend Developer Should Know About Webpage Rendering

2 Jul

Rendering has to be optimized from the very beginning, when the page layout is being defined, as styles and scripts play the crucial role in page rendering. Professionals have to know certain tricks to avoid performance problems.

This arcticle does not study the inner browser mechanics in detail, but rather offers some common principles. Different browser engines work differently, this would make a browser-specific study even more complicated.

How do browsers render a web page

We start with an overview of browser actions when rendering a page:

The DOM (Document Object Model) is formed from the HTML that is received from a server.
Styles are loaded and parsed, forming the CSSOM (CSS Object Model).
On top of DOM and CSSOM, a rendering tree is created, which is a set of objects to be rendered (Webkit calls each of those a “renderer” or “render object”, while in Gecko it’s a “frame”). Render tree reflects the DOM structure except for invisible elements (like the tag or elements that have display:none; set). Each text string is represented in the rendering tree as a separate renderer. Each of the rendering objects contains its corresponding DOM object (or a text block) plus the calculated styles. In other words, the render tree describes the visual representation of a DOM.
For each render tree element, its coordinates are calculated, which is called “layout”. Browsers use a flow method which only required one pass to layout all the elements (tables require more than one pass).
Finally, this gets actually displayed in a browser window, a process called “painting”.
When users interact with a page, or scripts modify it, some of the aforementioned operations have to be repeated, as the underlying page structure changes.

Repaint

When changing element styles which don’t affect the element’s position on a page (such as background-color, border-color, visibility), the browser just repaints the element again with the new styles applied (that means a “repaint” or “restyle” is happening).

Reflow

When the changes affect document contents or structure, or element position, a reflow (or relayout) happens. These changes are usually triggered by:

DOM manipulation (element addition, deletion, altering, or changing element order);
Contents changes, including text changes in form fields;
Calculation or altering of CSS properties;
Adding or removing style sheets;
Changing the “class” attribute;
Browser window manipulation (resizing, scrolling);
Pseudo-class activation (:hover).
How browsers optimize rendering

Browsers are doing their best to restrict repaint/reflow to the area that covers the changed elements only. For example, a size change in an absolute/fixed positioned element only affects the element itself and its descendants, whereas a similar change in a statically positioned element triggers reflow for all the subsequent elements.

Another optimization technique is that while running pieces of JavaScript code, browsers cache the changes, and apply them in a single pass after the code was run. For example, this piece of code will only trigger one reflow and repaint:

var $body = $(‘body’);
$body.css(‘padding’, ‘1px’); // reflow, repaint
$body.css(‘color’, ‘red’); // repaint
$body.css(‘margin’, ‘2px’); // reflow, repaint
// only 1 reflow and repaint will actually happen
However, as mentioned above, accessing an element property triggers a forced reflow. This will happen if we add an extra line that reads an element property to the previous block:

var $body = $(‘body’);
$body.css(‘padding’, ‘1px’);
$body.css(‘padding’); // reading a property, a forced reflow
$body.css(‘color’, ‘red’);
$body.css(‘margin’, ‘2px’);
As a result, we get 2 reflows instead of one. Because of this, you should group reading element properties together to optimize performance (see a more detailed example on JSBin).

There are situations when you have to trigger a forced reflow. Example: we have to apply the same property (“margin-left” for example) to the same element twice. Initially, it should be set to 100px without animation, and then it has to be animated with transition to a value of 50px. You can study this example on JSBin right now, but I’ll describe it here in more detail.

We start by creating a CSS class with a transition:

.has-transition {
-webkit-transition: margin-left 1s ease-out;
-moz-transition: margin-left 1s ease-out;
-o-transition: margin-left 1s ease-out;
transition: margin-left 1s ease-out;
}
Then proceed with the implementation:

// our element that has a “has-transition” class by default
var $targetElem = $(‘#targetElemId’);

// remove the transition class
$targetElem.removeClass(‘has-transition’);

// change the property expecting the transition to be off, as the class is not there
// anymore
$targetElem.css(‘margin-left’, 100);

// put the transition class back
$targetElem.addClass(‘has-transition’);

// change the property
$targetElem.css(‘margin-left’, 50);
This implementation, however, does not work as expected. The changes are cached and applied only at the end of the code block. What we need is a forced reflow, which we can achieve by making the following changes:

// remove the transition class
$(this).removeClass(‘has-transition’);

// change the property
$(this).css(‘margin-left’, 100);

// trigger a forced reflow, so that changes in a class/property get applied immediately
$(this)[0].offsetHeight; // an example, other properties would work, too

// put the transition class back
$(this).addClass(‘has-transition’);

// change the property
$(this).css(‘margin-left’, 50);
Now this works as expected.

Practical advice on opmitization

Summarizing the available information, I could recommend the following:

Create valid HTML and CSS, do not forget to specify the document encoding. Styles should be included into , and scripts appended to the end of the tag.
Try to simplify and optimize CSS selectors (this optimization is almost universally ignored by developers who mostly use CSS preprocessors). Keep nesting levels at a minimum. This is how CSS selectors rank according to their performance (starting from the fastest ones):
Identificator: #id
Class: .class
Tag: div
Adjacent sibling selector: a + i
Parent selector: ul > li
Universal selector: *
Attribute selector: input[type=”text”]
Pseudoclasses and pseudoelements: a:hover You should remember that browsers process selectors from right to left, that’s why the rightmost selector should be the fastest one — either #id or .class:
div * {…} // bad
.list li {…} // bad
.list-item {…} // good
#list .list-item {…} // good
In your scripts, minimize DOM manipulation whenever possible. Cache everything, including properties and objects (if they are to be reused). It’s better to work with an “offline” element when performing complicated manipulations (an “offline” element is one that is disconnected from DOM and only stored in memory), and append it to DOM afterwards.
If you use jQuery to select elements, follow jQuery selectors best practices.
To change element’s styles, modifying the “class” attribute is one of the most performant ways. The deeper in the DOM tree you perform this change, the better (also because this helps decouple logic from presentation).
Animate only absolute/fixed positioned elements if you can.
It is a good idea to disable complicated :hover animations while scrolling (e.g. by adding an extra “no-hover” class to ). Read an article on the subject.
For a more detailed overview, have a look at these articles:

How browsers work
Rendering: repaint, reflow/relayout, restyle
I hope you find this article useful!

All about this keyword in javascript

31 Jul

Conceptual Overview of this
When a function is created, a keyword called this is created (behind the scenes), which links to the object in which the function operates. Said another way, this is available to the scope of its function, yet is a reference to the object of which that function is a property/method.
Let’s take a look at this object:

var cody = {
living:true,
age:23,
gender:’male’,
getGender:function(){return cody.gender;}
};

console.log(cody.getGender()); // logs ‘male’

Notice how inside of the getGender function, we are accessing the gender property using dot notation (e.g cody.gender) on the cody object itself. This can be rewritten using this to access the cody object because this points to the cody object.

var cody = {
living:true,
age:23,
gender:’male’,
getGender:function(){return this.gender;}
};

console.log(cody.getGender()); // logs ‘male’

The this used in this.gender simply refers to the cody object on which the function is
operating.
The topic of this can be confusing, but it does not have to be. Just remember that, in general, this is used inside of functions to refer to the object the function is contained within, as opposed to the function itself (exceptions include using the new keyword or call() and apply()).
Important Notes
The keyword this looks and acts like any other variable, except you can’t modify it.
– As opposed to arguments and any parameters sent to the function, this is a keyword (not a property) in the call/activation object.
How is the Value of this Determined?
The value of this, passed to all functions, is based on the context in which the function is called at runtime. Pay attention here, because this is one of those quirks you just need to memorize.
The myObject object in the code below is given a property called sayFoo, which points to the sayFoo function. When the sayFoo function is called from the global scope, this refers to the window object. When it is called as a method of myObject, this refers to myObject.
Since myObject has a property named foo, that property is used.

var foo = ‘foo’;
var myObject = {foo: ‘I am myObject.foo’};

var sayFoo = function() {
console.log(this[‘foo’]);
};

// give myObject a sayFoo property and have it point to sayFoo function
myObject.sayFoo = sayFoo;
myObject.sayFoo(); // logs ‘I am myObject.foo’ 12

sayFoo(); // logs ‘foo’

Clearly, the value of this is based on the context in which the function is being called. Consider that both myObject.sayFoo and sayFoo point to the same function. However, depending upon where (i.e. the context) sayFoo() is called from, the value of this is different.
If it helps, here is the same code with the head object (i.e window) explicitly used.

window.foo = ‘foo’;
window.myObject = {foo: ‘I am myObject.foo’};
window.sayFoo = function() { ! console.log(this.foo); };
window.myObject.sayFoo = window.sayFoo;
window.myObject.sayFoo();
window.sayFoo();

Make sure that as you pass around functions, or have multiple references to a function, you realize that the value of this will change depending upon the context in which you call the function.
Important Note
All variables except this and arguments follow lexical scope.
The this Keyword Refers to the Head Object in Nested Functions
You might be wondering what happens to this when it is used inside of a function that is contained inside of another function. The bad news is in ECMA 3, this loses its way and refers to the head object (window object in browsers), instead of the object within which the function is defined.

In the code below, this inside of func2 and func3 loses its way and refers not to myObject but instead to the head object.

var myObject = {
func1:function() {
console.log(this); //logs myObject
varfunc2=function() {
console.log(this); //logs window, and will do so from this point on
varfunc3=function() {
console.log(this); //logs window, as it’s the head object
}();
}();
}
};

myObject.func1();

The good news is that this will be fixed in ECMAScript 5. For now, you should be aware of this predicament, especially when you start passing functions around as values to other functions.
Consider the code below and what happens when passing an anonymous function to foo.func1. When the anonymous function is called inside of foo.func1 (a function inside of a function) the this value inside of the anonymous function will be a reference to the head object.

var foo = {
func1:function(bar){
bar(); //logs window, not foo
console.log(this);//the this keyword here will be a reference to foo object
}
};

foo.func1(function(){console.log(this)});

Now you will never forget: the this value will always be a reference to the head object when its host function is encapsulated inside of another function or invoked within the context of another function (again, this is fixed in ECMAScript 5).
Working Around the Nested Function Issue
So that the this value does not get lost, you can simply use the scope chain to keep a reference to this in the parent function. The code below demonstrates how, using a variable called that, and leveraging its scope, we can keep better track of function context.

var myObject = {
myProperty:’Icanseethelight’,
myMethod:function() {
var that=this; //store a reference to this (i.e.myObject) in myMethod scope varhelperFunctionfunction(){//childfunction
var helperFunction function() { //childfunction
//logs ‘I can see the light’ via scope chain because that=this
console.log(that.myProperty); //logs ‘I can see the light’
console.log(this); // logs window object, if we don’t use “that”
}();
}
}

myObject.myMethod(); // invoke myMethod

Controlling the Value of this
The value of this is normally determined from the context in which a function is called (except when the new keyword is used – more about that in a minute), but you can overwrite/control the value of this using apply() or call() to define what object this points to when invoking a function. Using these methods is like saying: “Hey, call X function but tell the function to use Z object as the value for this.” By doing so, the default way in which JavaScript determines the value of this is overridden.

Below, we create an object and a function. We then invoke the function via call() so that the value of this inside the function uses myObject as its context. The statements inside the myFunction function will then populate myObject with properties instead of populating the head object. We have altered the object to which this (inside of myFunction) refers.

var myObject = {};

var myFunction = function(param1, param2) {
//setviacall()’this’points to my Object when function is invoked
this.foo = param1;
this.bar = param2;
console.log(this); //logs Object{foo = ‘foo’, bar = ‘bar’}
};

myFunction.call(myObject, ‘foo’, ‘bar’); // invoke function, set this value to myObject

console.log(myObject) // logs Object {foo = ‘foo’, bar = ‘bar’}

In the example above, we are using call(), but apply() could be used as well. The difference between the two is how the parameters for the function are passed. Using call(), the parameters are just comma separated values. Using apply(), the parameter values are passed inside of an array. Below, is the same idea, but using apply().

var myObject = {};

var myFunction = function(param1, param2) {
//set via apply(), this points to my Object when function is invoked
this.foo=param1;
this.bar=param2;
console.log(this); // logs Object{foo=’foo’, bar=’bar’}
};

myFunction.apply(myObject, [‘foo’, ‘bar’]); // invoke function, set this value
console.log(myObject); // logs Object {foo = ‘foo’, bar = ‘bar’}

What you need to take away here is that you can override the default way in which JavaScript determines the value of this in a function’s scope.
Using the this Keyword Inside a User-Defined Constructor Function
When a function is invoked with the new keyword, the value of this — as it’s stated in the constructor — refers to the instance itself. Said another way: in the constructor function, we can leverage the object via this before the object is actually created. In this case, the default value of this changes in a way not unlike using call() or apply().
Below, we set up a Person constructor function that uses this to reference an object being created. When an instance of Person is created, this.name will reference the newly created object and place a property called name in the new object with a value from the parameter (name) passed to the constructor function.

var Person = function(name) {
this.name = name || ‘johndoe’; // this will refer to the instanc ecreated
}

var cody = new Person(‘Cody Lindley’); // create an instance, based on Person constructor

console.log(cody.name); // logs ‘Cody Lindley’

Again, this refers to the “object that is to be” when the constructor function is invoked using the new keyword. Had we not used the new keyword, the value of this would be the context in which Person is invoked — in this case the head object. Let’s examine this scenario.

var Person = function(name) {
this.name=name||’johndoe’;
}

var cody = Person(‘Cody Lindley’); // notice we did not use ‘new’
console.log(cody.name); // undefined, the value is actually set at window.name
console.log(window.name); // logs ‘Cody Lindley’

The Keyword this Inside a Prototype Method Refers to a Constructor instance
When used in functions added to a constructor’s prototype property, this refers to the instance on which the method is invoked. Say we have a custom Person() constructor function. As a parameter, it requires the person’s full name. In case we need to access the full name of the person, we add a whatIsMyFullName method to the Person.prototype, so that all Person instances inherit the method. When using this, the method can refer to the instance invoking it (and thus its properties).
Here I demonstrate the creation of two Person objects (cody and lisa) and the inherited whatIsMyFullName method that contains the this keyword to access the instance.

var Person = function(x){
if(x){this.fullName = x};
};

Person.prototype.whatIsMyFullName = function() {
return this.fullName; // ‘this’ refers to the instance created from Person()
}

var cody = new Person(‘cody lindley’);
var lisa = new Person(‘lisa lindley’);

// call the inherited whatIsMyFullName method, which uses this to refer to the instance
console.log(cody.whatIsMyFullName(), lisa.whatIsMyFullName());

/* The prototype chain is still in effect, so if the instance does not have a
fullName property, it will look for it in the prototype chain.
Below, we add a fullName property to both the Person prototype and the Object
prototype. See notes. */

Object.prototype.fullName = ‘John Doe’;
var john = new Person(); // no argument is passed so fullName is not added to instance
console.log(john.whatIsMyFullName()); // logs ‘John Doe’

The take away here is that the keyword this is used to refer to instances when used inside of a method contained in the prototype object. If the instance does not contain the property, the prototype lookup begins.
Notes
– If the instance or the object pointed to by this does not contain the property being referenced, the same rules that apply to any property lookup get applied and the property will be “looked up” on the prototype chain. So in our example, if the fullName property was not contained within our instance then fullName would be looked for at Person.prototype.fullName then Object.prototype.fullName.

Best Javascript Practice to Follow

11 Oct

Keep it short, stupid!

You have read this a zillion times already. As a programmer/webmaster you might have applied this tip multiple times too but never forget this in case of JavaScript.

  • Use comments and white spaces while in development mode to keep your code readable.
  • Remove white spaces and comments before publishing your scripts in live environment. Also, try to shorten your variable and function names.
  • Consider using third party tools to compress your JavaScript code before publishing the same.

Think before you touch object prototypes

Appending new properties to object prototypes is one of the most common reasons for script failures.

yourObject.prototype.anotherFunction = ‘Hello’;
yourObject.prototype.anotherMethod = function () { … };

In above case all variables will be affected as they are inherited from “yourObject”. Such usage might cause unexpected behaviour. Henceforth, it is suggested to delete such modifications right after its usage:

yourObject.prototype.anotherFunction = ‘Hello’;
yourObject.prototype.anotherMethod = function () { … };
test.anotherMethod();
delete yourObject.prototype.anotherFunction = ‘Hello’;
delete yourObject.prototype.anotherMethod = function () { … };

Debug JavaScript Code

Even the best programmers make mistakes. To limit them, run your JavaScript code through a JavaScript debugger to make sure that you haven’t made any silly blunders that can easily be prevented.

Avoid Eval

Your JavaScript can work well without the use of “eval” function. For those not aware, “eval” gives access to JavaScript compiler. If a string is passed as parameter of “eval” then its result can be executed.

This will degrade your code’s performance though it acts as a boon during development phase. Avoid “eval” in live environment.

Minimize DOM access

DOM is one of the most complex APIs that slows down the code execution process. At times the webpage might not load or it might load incompletely. Better to avoid DOM.

Learn JavaScript before using JavaScript libraries

Internet is chock full of JavaScript libraries that perform various functions. Programmers end up using JavaScript libraries without understanding the side effects of the same. It is strongly advisable to learn the basics of JavaScript before using third party JavaScript libraries; otherwise, be prepared for disastrous results.

Never use “SetTimeOut” and “SetInterval” as alternatives to “Eval”

setTimeOut( “document.getID(‘value’)”, 3000);

In above code document.getID(‘value’) is used as a string that is processed within the “setTimeOut” function. This is similar to “eval” function which executes a string during every execution of code thus degrading performance. Henceforth, it is suggested to pass a function within such functions:

setTimeOut(yourFunction, 3000);

[] is better than “new Array();”

“A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object.” – Douglas Crockford, writer of JavaScript: Good Parts.

Suggested:

var a = [‘1A’,’2B’];

Avoid:

var a = new Array();
a[0] =  “1A”;
a[1] = “2B”;

Never use “var” multiple times

While initializing every variable programmers tend to use “var” keyword. Instead, it is suggested that you use commas to avoid redundancy of keywords and reduce code size:

var variableOne = ‘string 1’,
variableTwo = ‘string 2’,
variableThree = ‘string 3’;

Never Miss Semicolons

This is one of the programming bugs that can consume hours of debugging. Personally, I have spent hours looking for problems in my code when the reason was the missing semicolon