When developing Mobile Web Applications, even the seemingly marginal micro-optimizations can result in a noticeable performance improvement over time and, therefore should be implemented where possible. One could also argue (and rightly so) that this same principle applies when developing Web Applications on the Desktop; however, in the context of Mobile Web Experiences, such optimizations are essential, perhaps even obligatory on the developers part.
In a previous post from a few months back I discussed some of the benefits of function overwriting in JavaScript. One similar performance optimization I regularly employee is that of One-time function initializations.
Conceptually, an IIFE/em> is a rather simple pattern which can be broadly described as follows:
- An Immediate Function / Self-executing Function performs some initial test conditions.
- The Immediate Function returns an anonymous function which, in turn, returns the results of the test conditions. Alternately, the Immediate Function can just return the test condition results.
- The anonymous function returned is assigned to a function expression or, the test condition results are assigned directly.
An example in code illustrates just how simple this pattern is:
1 2 3 4 5 6 7 8 9 10 11 12 13 | var hasSomeFeature = (function() { // implement test logic... for example, testing // a feature's existence in the browser against // multiple vendor prefixes, etc. // return a function which returns the results, or // just return the result value if desired... return function() { // return results... }; }()); |
Practical implementation example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | var hasWebSockets = (function(window) { var prefixes = 'ms O Moz Webkit'.split(' '), n = prefixes.length, i = 0; for (; i < n; ++i) { if (window[prefixes[i] + 'WebSocket']) { return true; } } return 'WebSocket' in window; }(this)); |
Implementing Immediately-invoked Function Expressions are quite useful in many situations. Specifically, they are of most value when implemented for use-cases where conditions are too complex to assign to a variable directly and, when the conditions tested only need to be evaluated once, after which re-evaluating the condition would be redundant and unnecessary – such as certain feature detections.
As a general rule of thumb, if a condition or set of conditions can be tested once; that is, they are guaranteed to not change during the execution of the application and, the tests are too complex to maintain if directly assign to a variable, then implementing One-time function initializations are a small, yet simple and practical optimization.
{Sorry, Comments are currently Closed! }