50 JavaScript Tips PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

1

INTRODUCTION

This tip-list is for developers who are familiar with JavaSctipt basics and want to learn how to get more out of
JavaScript. Squeezing the most performance out of JavaScript is critical for businesses that rely on their
applications’ performance and uptime.

In the list we have compiled not only the most essential JavaScript performance tips but also the freshest ones
that will enhance web-based mobile applications. The list includes tips from Google, Nokia, Opera, Monitis and
several developers who work really hard to achieve the best possible performance of JavaScript.

A Monitis Publication

Monitis is a specialist provider of web and Cloud monitoring services that include website monitoring, site load
testing, transaction monitoring, application and database monitoring, Cloud resource monitoring, and server and
internal network monitoring within one easy-to-use dashboard. Over 100,000 users worldwide have chosen
Monitis as their provider of choice to increase uptime and user experience of their services and products. What
makes Monitis' solutions different is that they are fast to deploy, feature-rich in technology and provide a
comprehensive single-pane view of on-premise and off-premise infrastructure and applications.

Keep in touch

Publication of
2

1. EVALUATE LOCAL VARIABLES


Primarily, specific to IE, because local variables are found based on the most to the least specific scope and
can pass through multiple levels of scope, the look-ups can result in generic queries. When defining the
function scope, within a local variable without a preceding var declaration, it is important to precede each
variable with var in order to define the current scope in order to prevent the look-up and to speed up the
code.

2. CREATE SHORTCUT CODES TO SPEED UP CODING


For useful codes that are constantly being used, speeding up the coding process can be achieved by
creating shortcuts for longer codes, for example, document.getElementById. By creating a shortcut, longer
scripts will not take as long to code and will save time in the overall process.

3. MANIPULATE ELEMENT FRAGMENTS BEFORE ADDING THEM TO DOM


Before placing the elements to the DOM, ensure that all tweaks have been performed in order to improve
JavaScript performance. This will eliminate the need to set aside Prepend or Append jQuery APIs.

4. SAVE BYTES BY USING MINIFICATION


Reduce the file size of your JavaScript documents by removing characters (tabs, source code documents,
spaces etc.) without changing the functionality of the file.
There are a number of minification tools that can assist in this process, and have the ability to reverse the
minification. Minification is the process of removing all unnecessary characters from source code, without
changing its functionality.

5. DON’T USE NESTED LOOPS IF NOT REQUIRED


Avoid unwanted loops, such as for/while, in order to keep the JavaScript linear and to prevent from having to
go through thousands of objects. Unwanted loops can cause the browser to work harder to process the
codes and can slow down the process.

6. CACHE OBJECTS TO INCREASE PERFORMANCE


Many times, scripts will be repeatedly used to access a certain object. By storing a repeated access object
inside a user defined variable, as well as using a variable in subsequent references to that object,
performance improvement can be achieved immediately.

7. USE A .JS FILE TO CACHE SCRIPTS


By using this technique, increased performance can be achieved because it allows the browser to load the
script once and will only recall it from cache should the page be reloaded or revisited.

Publication of
3

8. PLACE JAVASCRIPT AT THE BOTTOM OF THE PAGE


Placing the scripts as low as possible in the page will increase the rendering progress, and also increase
download parallelization. The result is that the page will seem to load faster, and in some cases it can also
save on the total amount of code needed.

9. USE JQUERY AS A FRAMEWORK


Used for the scripting of HTML, jQuery is an easy to use JavaScript library that can help to speed up any
website. jQuery provides a large number of plug-ins that can quickly be used, by even novice programmers.

10. COMPRESS YOUR FILES WITH GZIP


GZip can reduce a JavaScript file considerably, saving bandwidth, and accelerate the response time.
JavaScript files can be very large, and without compression, it can bog down any website. Smaller files
provide a faster and more satisfying web experience.

11. DON’T USE “W ITH” KEYWORD


The “With” keyword is considered a black-sheep because it suffers from several flaws that can be very
frustrating. Although it makes the process of working with local properties simpler, “With” can make looking
up variables in other scopes more expensive.

12. MINIMIZE REQUESTS FOR HTTP


Minimize HTTP requests to render pages by combining external files and including JavaScript directly within
XHTML pages. Each time a unique HTTP takes a trip to a server, the result is a large number of delays.

13. IMPLEMENT EVENT DELEGATION


With Event Delegation, it becomes easier to use a single event handler to manage a type of event for the
entire page. Without using Event Delegation, large web applications can grind to a halt because of too many
event handlers. Benefits of Event Delegation include; less functionality to manage, fewer ties between code
and DOM, and less memory required to process.

14. DON’T USE THE SAME SCRIPT TWICE


Duplicate scripts will have a significant impact on performance. Duplicate scripts will create unnecessary
requests on HTTP, especially in the IE browser. Using a SCRIPT tag, in an HTML page, will help to avoid
accidentally duplicating scripts.

Publication of
4

15. REMOVE DOUBLE DOLLAR $$


Using “double dollar $$” function is not necessarily needed, when it comes to improving the speed of a
website.

16. CREATING REFERENCE VARIABLES


When working with a specific node repeatedly, it is best to define a variable with that particular note, instead
of switching to it repeatedly. This is not a significant enhancement but it can have a bigger impact on a large
scale.

17. INCREASE SPEED OF OBJECT DETECTION


A more efficient method to using Object Detection is to use a code created dynamically based off of object
detection, rather than performing object detection inside of a function.

18. WRITE EFFECTIVE LOOPS


Depending on the browser, the method used to write Loops can have a great effect on the performance of a
site. Improper writing of loops can slow down pages with lots of queries and running a number of loops in
parallel.

19. SHORTEN SCOPE CHAINS


Global scopes can be slow, because each time a function executes, it cause a temporary calling scope to be
created. JavaScript searchers for the first item in the scope chain, and if it doesn’t find the variable, it swells
up the chain until it hits the global object.

20. INDEX DIRECTLY TO NODELISTS


NodeLists are live and can take up a lot of memory, as they are updated when an underlying document
changes. Its quicker to index directly into a list, as a browser will not need to create a node list object.

21. DON’T USE ‘EVAL’


Although the “eval” function is a good method to run arbitrary code, each string that is passed to the eval
function has to be parsed and executed on-the-fly. This cost has to be paid every time the execution
reaches an eval function call.

Publication of
5

22. USE FUNCTION INLINING


Function Inlining helps to eliminate call costs, and replaces a function call with the body of the called
function. In JavaScript, performing a function call is an expensive operation because it takes several
preparatory steps to perform: allocating space for parameters, copying the parameters, and resolving the
function name.

23. IMPLEMENT COMMON SUB-EXPRESSION ELIMINATION (CSE)


Common sub-expression elimination (CSE) is a performance-targeted compiler optimization technique that
searches for instances of identical expressions and replaces them with a single variable holding the
computed value. You can expect that using a single local variable for a common sub-expression will always
be faster than leaving the code unchanged.

24. BUILD DOM NODE AND ALL ITS SUB-NODES OFFLINE


When adding complex content such as tables to a site, performance is improved by adding complex sub-
trees offline.

25. TRY NOT TO USE GLOBAL VARIABLES


Because the scripting engine needs to look through the scope, when referencing global variables from within
function or another scope, the variable will be destroyed when the local scope is lost. If variables in global
scope cannot persist through the lifetime of the script, the performance will be improved.

26. USE PRIMITIVE FUNCTIONS OPERATIONS VS. FUNCTION CALLS


Improved speed can be achieved in performance critical loops and functions by using equivalent primitive
functions instead of function calls.

27. DON’T RETAIN ALIVE REFERENCES OF OTHER DOCUMENTS


By not retaining alive references of other documents after the script has finished with them, faster
performance will be achieved. This is because any references to those objects from that document are not
to be kept in its entire DOM tree, and the scripting environment will not be kept alive in RAM. Thus the
document itself is no longer loaded.

28. USE XMLHTTPREQUEST


XMLHttpRequest helps to reduce the amount of content coming from the server, and avoids the

Publication of
6

performance impact of destroying and recreating the scripting environment in between page loads. Its is
important to ensure that XMLHttpRequest is supported, or otherwise it can lead to problems and confusion.

29. AVOID USING TRY-CATCH-FINALLY


Whenever the catch clause is executed, where the caught exception object is assigned to a variable, “try-
catch-finally” creates a new variable in the current scope at runtime. A number of browsers do not handle
this process efficiently because the variable is created and destroyed at runtime. Avoid it!

30. DON’T MISUSE FOR-IN


Because the “for-in” loop requires the script engine to build a list of all the enumerable properties, coding
inside for loop does not modify the array. It iterates pre-compute the length of the array into a variable len
inside for loop scope.

31. DOWNLOAD FASTER W ITH A FEW ADJUSTMENTS

When web pages have high amounts of varying content, it can cause pages significant lag time.
Components including images, style sheets and scripts often cause the loading process to slow down.

You can make your pages load faster by reducing the size of your images or changing the format from high-
resolution JPEG files to GIF or PNG format.

You can also clean your code, ridding it of unnecessary characters, including tabs, spaces and comments.
You can use one of the many free tools, like Clean CSS that reduces your code.

32. USING IMAGE MAPS MAY NOT BE W ORTHWHILE

Image maps can cause confusion for navigation to users of your webpage, and you want super-easy
navigation. Image maps are good for displaying information in image format, but only with grouped images.

Another downside of using image maps is that they are difficult to create and time-consuming. There is a
large amount of code — which can cause slower download and coordinates must have precision. Even
when you can see the image map, it can look confusing.

New alternatives to image maps include programs such as CSS Sprites or using in-line images.

33. DISPLAYING IMAGES W ITHOUT CAUSING CRASHES

A web page that hosts many images eats up computer resources and can cause crashes. Keep crashes
minimal by streamlining your code; keeping it simple and clean, host photos and other high-resolution
images on independent sites. A better option is to use CSS Sprites, which allows you to combine an
unlimited number of images while lowering the amount of HTTP requests for a single image, which speeds
the load time of retrieving images from one source instead of combining from separate locations.

Publication of
7

34. WHEN NOT USING JAVASCRIPT IS BETTER

JavaScript is a powerful tool used by many developers, but there are times that using it can slow down
pages, or worse, a browser could disable it and make the page look off to users.

Make sure you absolutely need to use JavaScript, because it may have compatibility issues. If you can
create a better result by using HTML and CSS, by all means use them, and only use JavaScript if the other
way does not work.

35. REDUCE REQUESTS – REDUCE W AIT

Just like asking ten questions when one would suffice is the same principle of HTTP requests. When you
receive all your information with one request, it makes load time faster.

For example, each HTTP request uses 500 bytes – and each received object uses 500 bytes plus
headers. Each additional request sent uses more bytes instead of one 500 byte request and
reply, you use thousands of bytes for the same-sized image.

Traditional imaging methods use spliced portions, which rejoins the pieces for end users. Each slice requires
a separate request; where, using image maps, inline images or CSS Sprites reduces HTTP requests and
speeds up the process by sending images in a single piece or fewer pieces.

36. OPTIMIZATION STRATEGIES FOR BETTER PERFORMANCE

It is important to rework one area of your website at a time, so you can check what changes help load times,
what elements you can work without and finding other time-consuming culprits, including server
performance issues.

Some programs that can help in the server-side process include HTTPWatch and Fiddler. Cuzillion helps
when you want to experiment with various configurations of your web page.

37. BEST THIRD-PARTY W EB HOSTS

You can reduce your HTTP requests by using third-party services. Allowing a third-party to host your images
and RSS feeds allows for one HTTP request and creates faster load times.

Some top third-party hosts allow users to look at your images in different sizes, according to their
preferences.

Flickr provides hotlinks you can embed on your web page, but you cannot directly link to each particular

size.

ImageShack offers free services, but you have to allow ads to show to enjoy that freedom.

Publication of
8

Mobypicture hosts your photos, allows you to keep all rights to your content and does not sell anything

without your direct permission.

Twitter has joined the image hosting game, but works with PhotoBucket so all the same rules apply.

When choosing third-party hosting make sure to read and heed all rules and regulations. If you worry about
copyrights and the company selling your content, find hosting that allows you to keep all rights to your
content and says so.

38. WAYS TO REDUCE IMAGE FILE SIZE

Large image files have the potential to overload servers and make web pages load slowly.

You can cut image sizes by using online services that make them smaller. Many online services allow you to
resize your images on their site without having to sign up for use. A couple of sites you can try to get started
include Shrinkpictures.com and JPEGreducer.com.

Another effective way to make images load faster is to change their format. You can use Paint or Photoshop
to convert files from JPEG photo-quality images to lower resolution GIFs.

When changing images from JPEG to GIF you lose high-definition quality, so using a GIF works well for
charts and 2-D images; whereas, JPEG preserves quality when needed.

39. WEB PAGE PROFILE TOOLS

The best websites offer quality content, quickly. It is important for you to analyze your site to make sure
download speeds stay fast. If you offer great information, but users have to wait, they often leave before the
page loads. When you depend on revenue from your web pages, users leaving early make your money
adventures slim.

Testing your web page loading time is usually a simple process. Monitor.Us provides a free enterprise-
grade page load monitor for its users. The monitor is testing not only JavaScript performance, but also a set
of other important metrics such as the load speed of different elements on your website, how internal and
external links are affected during loading etc
.

40. GOOD W EBPAGE SOURCE CODE CLEANERS

Remember that jumbled, extensive or incorrect code causes your pages to load slower or not at all. Using a
source code cleaner, helps you navigate your code, cut unnecessary information and find and correct errors.

HTML Optimizer at iWebTools site allows you to copy and paste your code, and it automatically optimizes
your code. It may not look as good as before you inserted it, but it can make load times faster.

HTML Tidy checks and cleans source files and works well within deeply nested HTML. It also works on hard-
to-read code, making it more comprehensive with user-selected options including indentation and word
wrap.

Publication of
9

Word 2000 HTML Cleaner works well for programmers who write code in MS Word 2000. For $79, you
receive source code ready for use in ASP application. Obviously, this code cleaner targets a specific
audience, but may help you save time with complex codes.

123 HTML Protector Software protects your web page code and prevents others from using your source
code, scripts, links and images. With this program, it makes it difficult for users to manipulate your code,
which could wreak havoc on your pages.

41. CONVERTING DECIMALS TO HEX OR OCTAL AND VICE VERSA


Are you writing separate functions for hex (or octal) conversions? Stop. This can be easily done with existing
methods:
(int).toString(16); // converts int to hex, eg 12 => "C"
(int).toString(8); // converts int to octal, eg. 12 => "14"
parseInt(string, 16) // converts hex to int, eg. "FF" => 255
parseInt(string, 8) // converts octal to int, eg. "20" => 16

42. JAVASCRIPT VERSION DETECTION


Are you aware which version of Javascript your browser supports? If not, check Javascript Versions sheet
from Wikipedia. For some reason, features in Javascript version 1.7 are not widely supported. However,
most browsers released within a year support features in version 1.8 (and in 1.8.1). Note: all the versions of
Internet Explorer (8 and older) supports only Javascript version 1.5. Here’s a tiny script both for detecting the
version of Javascript via feature detection. It also allows checking support for specific version of Javascript:

Publication of
10

var JS_ver = [];

(Number.prototype.toFixed)?JS_ver.push("1.5"):false;

([].indexOf && [].forEach)?JS_ver.push("1.6"):false;

((function(){try {[a,b] = [0,1];return true;}catch(ex) {return


false;}})())?JS_ver.push("1.7"):false;

([].reduce && [].reduceRight && JSON)?JS_ver.push("1.8"):false;

("".trimLeft)?JS_ver.push("1.8.1"):false;

JS_ver.supports = function()

if (arguments[0])

return (!!~this.join().indexOf(arguments[0] +",") +",");

else

return (this[this.length-1]);

alert("Latest Javascript version supported: "+ JS_ver.supports());

alert("Support for version 1.7 : "+ JS_ver.supports("1.7"));

43. USING DOCUMENT.CREATEDOCUMENTFRAGMENT()


You may need to dynamically append multiple elements into document. However, appending them directly
into document will fire redrawing of whole view every time, which causes perfomance penalty. Instead, you
should use document fragments, which are appended only once after completion:

Publication of
11

function createList() {

var aLI = ["first item", "second item", "third item",

"fourth item", "fith item"];

// Creates the fragment

var oFrag = document.createDocumentFragment();

while (aLI.length) {

var oLI = document.createElement("li");

// Removes the first item from array and appends it

// as a text node to LI element

oLI.appendChild(document.createTextNode(aLI.shift()));

oFrag.appendChild(oLI);

document.getElementById('myUL').appendChild(oFrag);

44. DEFER PARSING OF JAVASCRIPT


In order to load a page, the browser must parse the contents of all <script> tags, which adds additional time
to the page load. By minimizing the amount of JavaScript needed to render the page, and deferring parsing
of unneeded JavaScript until it needs to be executed, you can reduce the initial load time of your page.

Publication of
12

45. PREFER ASYNCHRONOUS RESOURCES


Fetching resources asynchronously prevents those resources from blocking the page load. When a browser
parses a traditional script tag, it must wait for the script to download, parse, and execute before rendering
any HTML that comes after it. With an asynchronous script, however, the browser can continue parsing and
rendering HTML that comes after the async script, without waiting for that script to complete. When a script
is loaded asynchronously, it is fetched as soon as possible, but its execution is deferred until the browser's
UI thread is not busy doing something else, such as rendering the web page. JavaScript resources that
aren't needed to construct the initial view of the web page, such as those used for tracking/analytics, should
be loaded asynchronously. Some scripts that display user-visible content may also be loaded
asynchronously, especially if that content is not the most important content on the page (e.g. it is below the
fold).

46. LEVERAGE PROXY CACHING


Enabling public caching in the HTTP headers for static resources allows the browser to download resources
from a nearby proxy server rather than from a remote origin server.

47. DON'T INCLUDE A QUERY STRING IN THE URL FOR STATIC RESOURCES.
Most proxies, most notably Squid up through version 3.0, do not cache resources with a "?" in their URL
even if a Cache-control: public header is present in the response. To enable proxy caching for these
resources, remove query strings from references to static resources, and instead encode the parameters
into the file names themselves.

48. DON'T ENABLE PROXY CACHING FOR RESOURCES THAT SET COOKIES.
Setting the header to public effectively shares resources among multiple users, which means that any
cookies set for those resources are shared as well. While many proxies won't actually cache any resources
with cookie headers set, it's better to avoid the risk altogether. Either set the Cache-Control header to private
or serve these resources from a cookieless domain.

49. LOOP
When simple iterations are required, in other words repeating an action n times, we will often use a while
instead of a for loop.

for (var i = 0; i<1000; i++) {

// do your stuff

vs

Publication of
13

var i = 1000;

while (i--) {

// do your stuff

Anyone who has to deal with (read: support) Internet Explorers will say that the while loop is faster. That is
true for all IE9 and older. New browsers, however, cancel this out in favour of the for loop. Yet, the
performance increase in percentage is higher than the one found in IEs.

50. ACCESSING OBJECT PROPERTIES


Repeated access to nested object properties is, logically, going to introduce performance drawbacks. Here
is what I mean:

for (var i in App.view.tablet.Viewport) {

console.log(App.view.tablet.Viewport[i]);

Let’s dissect the line inside the for loop. I am telling browser to access App object, then find view reference
and access it, then find tablet and open it to access Viewport. That’s four references so far plus the last one
of the value of i. To reach each reference our JavaScript code communicates with the browser, the browser
communicates through its internal components to the OS and finally to reach the desired memory allocation
in RAM. And we do this five times.

Instead, let’s cache the static part, or the first four steps and see what it brings us:

var vp = Ext.view.tablet.Viewport;

for (var i in vp) {

console.log(vp[i]);

Publication of
14

SUMMARY

As mobile devices become more popular among users, it is important to optimize applications for mobile
usage. The need for continually optimizing performance in JavaScript is obvious but as we take into
consideration the complexities of this in regards to mobile applications it becomes imperative.. This tip list is
compiled with mobile performance in mind, so that developers could push their applications’speed and
overall performance even further.

Publication of

You might also like