Javascript tips I.

Today I stumbled on two articles about Javascript dos and don’ts. Most
of it is common sense and practiques you develop naturally if you mean
it seriously with Javascript. However there were a couple of tricks
that caught my attention.
 
1. Smart looping through an array of elements:

var rows = document.getElementsByTagName('tr'); for( var i = 0, row; row = rows[i]; i++ ) {   // do stuff with rows here }

2. Reduce reflow.
 
3. Cache complex objects:

var cached = (function () {   var privateObj = {    option1: 500,    option2: 1000   };   return function (arg) {    // foo();   }; })();

Now you can do

cached()

which will have access to the variables defined in the privateObj. This object is created only once, hence the speed-up.

 

 

Advertisements

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s