Artur Rychlewicz
Artur Rychlewicz

Reputation: 505

Does spliting large IIAF to smaller functions improve performance?

I was checking Google Search page and I noticed that they do something like below:

(function(){
    window.google={}; // few keys (none of the keys is function)
})();

// immediately after, same script tag
(function(){
    google.x = function(){ /* ... */ };
    google.y = function(){ /* ... */ };
})();
// anonymous function invocations repeat

Is it possible that splits like that can improve overal performance at all? Second question - would the performance gains be any different if one would put each function in separate <script> tag?

Upvotes: 0

Views: 172

Answers (1)

Parris
Parris

Reputation: 18408

No performance benefit, in fact, it should be slightly slower. In general, IIFEs are used to protect against globals being accidentally created. The IIFE in this example is partially useless since it is setting up globals.

I suspect this is the result of having a base.html template (or something like that), and some application/page specific scripts being added in dynamically.

I imagine the base.html file might look something like this:

<body>
...
<script>
  {{> iife script="window.google={}" }}
  {{#each scripts}}
      {{> iife script=script }}
  {{/each}}
</script>
</body>

I'm using handlebars, but it could be any templating language. The {{> iife }} code represents rendering a "partial" template. Essentially, this would just wrap up any code in an IIFE. In the above example, we also loop through a variable called "scripts". Which is an array of strings.

In some specific app/page new inline scripts might be added like this:

scripts.push('google.x = function(){ /* ... */ };');

This allows for easy creation of new applications/pages that have all the same default settings/configuration. It also lets them add scripts to pages in a consistent way.

Upvotes: 1

Related Questions