curious1
curious1

Reputation: 14717

Improving Javascript performance by wrapping and reducing executed statements

I am doing a website. Many pages depend on Javascript. At this moment, I have individual Javascript files (many are quite large) for respective pages. The following is an example for one individual Javascript file for a particular page (suppose this page has <body id="page_1">):

$('#id_1').click(function(e) {
   ...
});
$('#id_2').click(function(e) {
   ...
});
....
$('#id_N').click(function(e) {
   ...
});
...
//there can be many functions like this one
function abc() {
}

For website performance, I am going to combine all these individual Javascript files into one file. Before doing this, I am going to wrap each Javascript file to make it only applicable to its target page in the following way (adding an IF statement):

if ($('#page_1').length > 0) {

    $('#id_1').click(function(e) {
       ...
    });
    $('#id_2').click(function(e) {
       ...
    });
    ....
    $('#id_N').click(function(e) {
       ...
    });
    ...
    //there can be many functions like this one
    function abc() {
    }
}

I think this can help in three ways in case of a combined Javascript file:

  1. Reduce potential conflict with other individual Javascript files
  2. Reduce the possibility of affecting html elements on other pages
  3. Improve the speed of processing the combined Javascript file because the browser will not have to execute many statements not applicable for a page.

Am I right in these points? Hope to hear from experts out there so that I can do the right thing.

Thanks and regards.

Upvotes: 0

Views: 31

Answers (1)

Blindy
Blindy

Reputation: 67388

#1 and #2 depends on your code, but about #3 it would be a small increase in loading speed, yes. Very, very small though since looking up selectors is blazing fast and if the selector doesn't match anything, all functions applied on it won't execute.

Upvotes: 1

Related Questions