Book Image

PHP Ajax Cookbook

Book Image

PHP Ajax Cookbook

Overview of this book

Table of Contents (16 chapters)
PHP Ajax Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Caching of objects


As JavaScript code has to run on client machines, the code-level optimizations are very important. The most important of these is caching or buffering of calculations and objects. This basic optimization is often overlooked.

Getting ready

We'll need to identify the repetitive function calls to cache the results; that will speed up the code performance.

How to do it...

var a = Math.sqrt(10);
var b = Math.sqrt(10);

Here, in this case, we repeatedly calculate the same sqrt(10) and store it in different variables. This is overkill; as you know, it could be written as follows:

var sqrt_10 = Math.sqrt(10);
var a = sqrt_10, b = sqrt_10;

Similarly, especially in the world of selector-based frameworks, it's advisable to cache or buffer the selector objects. For example, consider the following HTML markup:

<a href="#" id="trigger">Trigger</a>
<div id="container">
Container
</div>

Here's the jQuery code that hides the container initially; when the trigger link is clicked...