Wednesday, July 17, 2013

Fine Tune JavaScript - Improve Performance with Local Variables

We all know literal values and local variables can be accessed very quickly, whereas array items and object members take longer. But what is a reason behind it? In this article I will talk about how you can improve performance of your existing code with the use of local variables wisely.
Let's start with a simple example -

function updateClass(){
    var divList = document.getElementsByTagName("div");
    for(var counter = 0; counter<divList.length; counter++){
        divList[counter].className = document.body.className;  
    }
}

Before improving the performance of the function let's see what all artifacts/internal objects are created when the function created and executed. When the function is created, it's [[Scope]] property is initialized with a collection of global variables. More info about Scope Chain is available in the earlier post - JavaScript Jargon - Scope Chain, Execution Context and Activation Object
Some of the global variables which are available in the [[Scope]] object are -
  • this
  • window
  • document
  • updateClass
When the function is executed, a new internal object - Execution Context, is created which has it's own scope chain. This scope chain is initialized with the objects present in the scope chain which was created when the function itself was created. Once the initialization is over, another internal object - Activation object, is created and pushed on top of the execution object's scope chain. The activation object acts as the variable object for this execution and contains entries for all local variables, named arguments, the arguments collection, and this. In this case activation object will have -
  • this
  • divList
  • counter
  • arguments[] - it null in this case as there are no arguments passed to the function
The scope chain of the execution context object now will have two entries - Activation Object and Global Object.

Each time a variable is encountered during the function’s execution, the process of Identifier Resolution takes place to determine where to retrieve or store the data. It first starts with searching the variable in the execution object's scope chain and goes all the way down to the global object, if it is not found in the first place. It is this search process that affects performance. The deeper into the execution context’s scope chain an identifier exists, the slower it is to access for both reads and writes. Since local variables are always available in the activation object, therefor their access is always fastest as compared to the global variable which are available in the end of the chain.
A good rule of thumb is to always store out-of-scope values in local variables if they are used more than once within a function. In the function above, the document object is being accessed multiple time, Since the document object is a global variable, therefore every time it is being accessed you have to pay the performance penalty. Based on this information here is the improved version of the function -

function improvedUpdateClass(){
    var docObject = document;
    var divList = docObject.getElementsByTagName("div");
    var className = docObject.body.className;
    var divCount = divList.length;
  
    for(var counter = 0; counter<divCount; counter++){
        divList[counter].className = className;  
    }
}
In this improved version, instead of accessing the document object  multiple times, it's reference is being stored in a local variable - docObject, which is being accessed in rest of the function. Also we have created a local variable for storing body's class name - className, which is again improves performance.

Tuesday, July 16, 2013

JavaScript Jargon - Scope Chain, Execution Context and Activation Object

In JavaScript every function is represented as an object - an instance of the JavaScript Function. Like any other object, it also has some properties which can be accessed programmatically and  few which are used only by the JavaScript engines. One of the properties is [[Scope]] which is available only for the engines.
This internal [[Scope]] property is a collection of objects which represents the scope/environment in with the function is defined. The collection of objects, which determines the data which the function can access, is known as function's Scope Chain. Each object in the Scope Chain is called as Variable Object. A Variable Object holds the variables, in the form of key-value pair, which a function can access.
Let's understand it better with the following example -

function multiply(arg1, arg2){
     var result = arg1 * arg2;
    return result;
}

In this case as soon as the function is created, it's Scope Chain is initialized with a variable object - Global Object. A Global Object is a collection of data, available outside the scope of the function, which the function can access, like - window, document, navigator etc..
At the time of function execution, an internal object  - Execution Context, is created. Execution Context represents the environment in which the function is executed. Once the execution is completed, this object is destroyed. Execution Context is created per execution. Therefore if the same function is executed multiple times, multiple Execution Context objects are created.
Execution Context object also has it's own Scope Chain object which is initialized with the data present in the function's [[Scope]] object. Later a new object - Activation Object, is created and pushed on top of the Global Object in the Execution Context's Scope Chain.
The internal Activation Object holds data specific to the function - local variable/s, named argument/s, argument[] and this. Again this object is destroyed once the function execution is completed. .


Thursday, July 11, 2013

Fine Tune JavaScript - On Demand Script loading

Dynamically loading external scripts is one of the techniques used to write non-blocking JavaScript code.  It is a three step process –

  • Create an element for the <script> tag.
  • Set the source of the <script> element as the location of the external script file.
  • Append the <script> element to either of the two - <body> or <head>, tag.

In this example, we try to load the external script dynamically –

  var scriptObj = document.createElement('script');
  scriptObj.src = 'external-script.js';
  document.getElementsByTagName("head")[0].appendChild(scriptObj);


This new <script> element loads the source file external-script.js. The file begins downloading as soon as the element is added to the page. The important thing about this technique is that the file is downloaded and executed without blocking other page processes, regardless of where the download is initiated.  

You can also attach event handlers to take action when the script is downloaded completely. But there is slight different between the event which is being fired in case of IE and rest of the browsers (Firefox, Opera, Chrome, Safari ). Firefox, Opera, Chrome, and Safari 3+ all fire a load event when the src of a
<script> element has been retrieved. In case of IE, readystatechange event is triggered.

This example takes care of both the use-case –

        var script = document.createElement("script")
        script.type = "text/javascript";
        
        //Internet Explorer
        if (script.readyState){
            script.onreadystatechange = function(){
                if (script.readyState == "loaded" || script.readyState == "complete"){
                    script.onreadystatechange = null;
                    alert("Script loaded.");
                }
            };

        } else{
            //Firefox, Opera, Chrome, Safari 3+
            script.onload = function(){
                alert("Script loaded!");
            };

        }
        script.src = "file1.js";
        document.getElementsByTagName("head")[0].appendChild(script);

 


 


Fine Tune JavaScript - Defer Script execution

Deferring execution of scripts is one of the techniques used to write non-blocking JavaScript code.  HTML provides the defer attribute for the <script> tag. When present, it specifies that the script is executed when the page has finished parsing/loading.  

Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).

For example this case the script will not run until after the page has loaded:

 

  <script src="demo_defer.js" defer></script>

 

As soon as the <script> tag is parsed, JavaScript file will begin downloading, but the code will not be executed until the DOM has been completely loaded (before the onload event handler is called). It doesn’t block the browser’s other processes, and so these files can be downloaded in parallel with others on the page.

 

 


Fine Tune JavaScript - Placement of SCRIPTs

We have been writing JavaScript code from ages. But have you ever think of OPTIMIZING it? How many of you know about the Design Patterns for JavaScript? " WHAT!!! Design Patterns for JavaScript? Do they really exists?". Yes that's what might have come in your mind. Well to be very honest, most of the UI developers, never focus on the performance of the JavaScript.

Despite advancements in core JavaScript execution time, there are still aspects of JavaScript that the new age JavaScript engines don’t handle.In this and next few articles I will focus on how to improve performance of the JavaScript code we write. I will share techniques and approaches which will address different aspects of JavaScript, including execution time, downloading, DOM interaction, page life cycle, and more.

This article talks about improving page loading and execution time.

Let's start with a simple example -

<html>
    <head>
        <title>Simple Script </title>
        <script src="file1.js"></script>
        <script src="file2.js"></script>
        <link rel="stylesheet" type="text/css" href="styles.css">
    </head>
    <body>
        <p>Hello world!</p>
    </body>
</html>

Can you guess what's wrong with this code? Well the answer is - inefficient script positioning.

Usually we all keep all the <script> tags that are used to load external JavaScript files along with <link> tags to load external CSS files and other meta information about the page in the <head> tag. The theory was that it’s best to keep as many style and behavior dependencies together, loading them first so that the page will come in looking and behaving correctly.

Today most browsers use a single process for both user interface (UI) updates and JavaScript execution, so only one can happen at any given moment in time. The longer
JavaScript takes to execute, the longer it takes before the browser is free to respond to user input. this means that the very presence of a <script> tag is enough to make
the page wait for the script to be parsed and executed. Whether the actual JavaScript code is inline with the tag or included in an external file is irrelevant; the page download
and rendering must stop and wait for the script to complete before proceeding. This is a necessary part of the page’s life cycle because the script may cause changes to the page while executing.

In the example above each <script> tag blocks the page from continuing to render until it has fully downloaded and executed the JavaScript code, the overall performance of this page will suffer. Keep in mind that browsers don’t start rendering anything on the page until the opening <body> tag is encountered. Putting scripts at the top of the page in this way typically leads to a noticeable delay, often in the form of a blank white page, before the user can even begin reading or otherwise interacting with the page.

Although new age browsers support parallel downloading of the external JavaScript files but it still blocks downloading of other resources, such as Images. And even though downloading a script doesn’t block other scripts from downloading, the page must still wait for the JavaScript code to be downloaded and executed before continuing.

So what's the solution to this problem? Well the best solution to this problem is to place all <script> tags as close to the bottom of the <body> tag as possible so as not
to affect the download of the entire page -

<html>
<head>
<title>Simple Script</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <p>Hello world!</p>
    <script src="file1.js"></script>
    <script src="file2.js"></script>
</body>
</html>

In this case even though the script downloads will block one another, the rest of the page has already been downloaded and displayed to the user so that the entire page isn’t perceived as slow.

That's the first lesson for you!!!

 


Tuesday, September 21, 2010

Syntax Highlighter - Easy way to insert code to your Blog

Are you unable to NEATLY insert html/code in your blog? Yes I am talking about NEATLY injecting code to your blogger’s post. There are so many ways through which you can insert the code, but displaying it in a CLEAN and NEAT way is a common problem.
Solution to your problem is – SyntaxHighlighter. SyntaxHighlighter is designed to enhance the appearance for your injected code so it becomes more presentable and readable. Follow the simple steps listed below to HIGHLIGHT your code:

Download the latest version (2.1.364) of SyntaxHighlighter from here

Extract the archive any where on your machine. Since your blogger will require scripts and stylesheets while formatting the injected code, therefore you have to upload the required files to some file hosting server. I am using MyDataNest to host the files. Other option is to use the files directly from the Amazon S3 where all the files are hosted for SyntaxHighlighter. To know more about how to use Amazon S3 hosting server, check out - Hosting details

If you are uploading files to your hosting server, then you have to make few changes in shCore.css. In this file location of all the .png files are relative to shCore.css. You need to replace it with the url generated by your hosting server for the .png files. For example:







Code from the original shCore.css:
.syntaxhighlighter .toolbar .item.viewSource
{
 background-image: url(page_white_code.png) !important;
}

Replaced with the new URL:
.syntaxhighlighter .toolbar .item.viewSource
{
 background-image: url(“http://www.mdn.fm/files/203599_tgby9/page_white_code.png”) !important;
}


Beauty of SyntaxHighlighter is that it is not limited to styling HTML. It also supports plenty of other languages like:
  • XML
  • PHP
  • SQL
  • Java
  • AppleScript

So if you want to style PHP code then use PHP specific script file - shBrushPhp.js

I this example I will be formatting javascript code. Therefore I’ll be using files which are required to format javascript. To format javascript, I need following files:
Script Files:
  • shCore.js
  • shBrushJScript.js

Stylesheets:
  • shCore.css
  • shThemeDefault.css

Insert following piece of code in your blogger’s post before you inject the code to be formatted:
<div style="display:none">
<script type="text/javascript" src="http://www.mdn.fm/files/203429_cxbgd/shCore.js"></script> 
<script type="text/javascript" src="http://www.mdn.fm/files/203418_pxjga/shBrushJScript.js"></script> 
<script type="text/javascript" src="http://www.mdn.fm/files/203407_1hmq9/shBrushBash.js"></script> 
<script type="text/javascript" src="http://www.mdn.fm/files/203409_yhno5/shBrushCpp.js"></script> 
<style type="text/css"> 
@import url("http://www.mdn.fm/files/203601_zvagb/shCore.css"); 
@import url("http://www.mdn.fm/files/203375_cvxdp/shThemeDefault.css"); 
</style> 
<script type="text/javascript">  
SyntaxHighlighter.all(); 
</script> 
</div>

Now all you have to do is to insert your code between <pre></pre> tags. Also you need to specify the type of bursh - language code. For example, to style javascript code, bursh type should be jscript:
<pre class="brush: jscript">
$('a').click(function(){
//do something
})
</pre>

Monday, June 28, 2010

jQuery By Examples: Load data through Ajax - 2

In this example, I am populating a Drop Down list asynchronously through the .load() method. Advantage of loading data through .load() method is that it allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded. Therefore instead of loading the complete document, here I can load specific portion of the document. In this example first I am getting the list of all the Tags available under the Index section of the page. This is achieved through the special URL syntax used in the .load() method. The next setp is to load the data in a temporary div. Here is the sample data available in the div element:

<li>
<a dir='ltr' href='http://myerrorslog.blogspot.com/search/label/Application%20Server%20FAQs'>Application Server FAQsa>
<span dir='ltr'>(1)span>
li>
<li>
<a dir='ltr' href='http://myerrorslog.blogspot.com/search/label/Articles'>Articlesa>
<span dir='ltr'>(1)span>
li>

Once the data is loaded in the div, I am populating the drop down by creating option element dynamically. Every option has following attributes:
text - text from the a tag
value - href from the a tag

Once all the li elements are process, the temp div is removed.

Now when a user, clicks the button to get the posts for the selected Tag, data is loaded again asynchronously through the .load() method. Instead of loading the complete post, I am loading specific part of the post.

Demo:








Click the link to show code fragment