---
{
	"title": "Optimize your JavaScript, CSS and HTML code",
	"language": "en",
	"description": "How to optimize your JavaScript, CSS and HTML code",
	"altLangPrefix": "opt",
	"dateModified": "2014-04-04"
}
---
<span class="wb-prettify all-pre"></span>
<p>How to optimize your JavaScript, CSS and HTML code. Please add to and improve upon the techniques that already listed.</p>

<section>
	<h2>Overview</h2>
	<p>Code optimization is now an important task with the Web Experience Toolkit taking a mobile-first approach in version 4.0. Where sluggish code may have minimal impact on desktop browser performance, it can result in very noticeable delays on mobile devices. That is why a main focus of WET v4.x is performance optimization.</p>
	<p>The WET v4.x framework is already heavily optimized using code minification, consolidation, CSS spriting and Base64 encoding. All of these result in significant performance increases but can still be bogged down by bloated and sluggish code. This page provides many tips for ensuring your code is as efficient as possible.</p>
</section>

<section>
	<h2>JavaScript code optimization</h2>
	<ul>
		<li><strong>Minimize the use of jQuery:</strong> jQuery can be a big help with DOM traversal and complex scripting scenarios but can be sluggish when dealing with simple and straight forward coding scenarios. There is a performance cost to each jQuery object created and jQuery wrapper methods for native JavaScript operations. Avoid creating jQuery objects wherever possible, especially in loops.</li>
		<li>
			<strong>Optimize your loops:</strong> The fastest loops in JavaScript are cached for loops (length cached outside the loop). Avoid using jQuery loops (e.g., <code>each()</code>) wherever possible as there is a lot of overhead. In the case of jQuery objects, use <code>.get()</code> to get an array of DOM objects upon which reverse while and cached for loops can be used.
			'''Cached for loop (length cached outside the loop):'''
<pre><code>var i,
	len = myArray.length;
for ( i = 0; i !== len; i += 1 ) {

	// do something with array item
	console.log( myArray[ i ] );
}</code></pre>
		</li>
		<li><strong>if/else versus switch statements:</strong> When deciding how to control your program flow, it's important to consider the number of different conditions you need to test. If there are only 1 or 2 conditions, if/else statements are generally faster. However, once you have 3 or more conditions to test, a switch statement is the faster option. Your if/else and switch statements should also be organized so that the most common conditions appear at the top of the if/else block or switch statement (see the jsPerf <a rel="external" href="https://jsperf.com/program-flow-statements">if/else versus switch test case</a>).</li>
		<li><strong>Cache DOM elements, jQuery objects and object/array values:</strong> There is a lot of overhead to performing DOM searches, creating jQuery objects, and retrieving object/array values. Minimize the impact by caching the results where those results will be used more than once. It is best to store those results in local variables and reuse those variables.</li>
		<li>
			<strong>Minimize reflow:</strong> Every change you make to the DOM has a significant performance cost as it causes page reflow. Minimize this cost by doing all the changes in a single operation to trigger reflow only once versus multiple operations which trigger reflow multiple times. This can be done in the following ways:
			<ul>
				<li>Put all the changes in a string or object and then append it to the DOM or replace part of the DOM with that string or object.</li>
				<li>Detach an element from the DOM, make the changes to it, then reattach it to the DOM.</li>
			</ul>
		</li>
		<li><strong>Avoid global DOM searches:</strong> The performance cost is much greater when searching the whole DOM rather than searching only a small part of it. If you already have a cached search, then take advantage of it and search from that point rather than searching the whole DOM again. For instance if you already have the search for the <code>.button</code> class already cached in the variable $buttons, then do <code>$buttons.find( "a.mybutton" )</code> to find the a elements versus <code>$( "a.mybutton" )</code>. Where possible, use native JavaScript for searching such as <code>getElementById</code> and <code>getElementsByTagName</code>.</li>
		<li><strong>Optimized DOM searches first, filtering later:</strong> The fastest DOM searches in JavaScript are by id and tag name because of the native JavaScript function <code>getElementById</code> and <code>getElementsByTagName</code>. Take advantage of this performance by doing optimized searches first then filtering later. For instance, instead of <code>.find( "a[href=*'url_fragment']" )</code> do <code>.find( "a" ).filter( "[href=*'url_fragment']" )</code>.</li>
		<li>
			<strong>Binding multiple events to an element:</strong> When binding multiple events to an element, it is faster to bind all events to a single event handler. You can then use the event's type property to determine which event has been triggered (see the jsPerf <a rel="external" href="https://jsperf.com/combined-or-separate-event-handlers">handling multiple events test case</a>).
<pre><code>// Faster: single event handler for both events
$( "#elem" ).on( "mouseover mouseout", function( event ) {
	if ( event.type === "mouseover" ) {

		// mouseover
	} else {

		// mouseout
	}
});

// Slower: separate event handler for each events
var $elem = $( "#elem" );
$elem.on( "mouseover", function( event ) {

	// mouseover
});
$elem.on( "mouseout", function( event ) {

	// mouseout
});</code></pre>
		</li>
	</ul>

	<section>
		<h3>Testing your optimizations</h3>
		<p>To test your optimization changes, wrap a block of code with the following two lines of code.</p>
		<pre><code>var test = ( new Date() ).getTime();
// Code to test
console.log( ( new Date() ).getTime() - test );</code></pre>
		<p>Another option is to use a site like <a rel="external" href="https://jsperf.com/">jsPerf</a> to benchmark different JavaScript code snippets.</p>
	</section>

	<section>
		<h3>jsPerf Test Cases</h3>
		<ul>
			<li><a rel="external" href="https://jsperf.com/combined-or-separate-event-handlers/3">Combined vs. Separate Event Binding</a></li>
			<li><a rel="external" href="https://jsperf.com/program-flow-statements">if/else versus switch statements</a></li>
			<li><a rel="external" href="https://jsperf.com/jep-vs-direct-binding">jQuery Event Binding: Document vs. Element</a></li>
			<li><a rel="external" href="https://jsperf.com/jquery-mobile-panel-popup">jQuery Mobile Panel vs. Popup Open</a></li>
		</ul>
	</section>

	<section>
		<h3>Additional techniques</h3>
		<ul>
			<li><a rel="external" href="https://24ways.org/2011/your-jquery-now-with-less-suck">Your jQuery: Now With 67% Less Suck</a></li>
			<li><a rel="external" href="https://hungred.com/useful-information/jquery-optimization-tips-and-tricks/">8 jQuery Optimization Tips and Tricks</a></li>
			<li><a rel="external" href="http://jonraasch.com/blog/10-advanced-jquery-performance-tuning-tips-from-paul-irish">10 Advanced jQuery Performance Tuning Tips from Paul Irish</a></li>
			<li><a rel="external" href="https://developers.google.com/speed/articles/optimizing-javascript">Optimizing JavaScript code</a></li>
			<li><a rel="external" href="https://desalasworks.com/javascript-performance-techniques/">25 Techniques for Javascript Performance</a></li>
			<li><a rel="external" href="http://jonraasch.com/blog/10-javascript-performance-boosting-tips-from-nicholas-zakas">10 Javascript Performance Boosting Tips from Nicholas Zakas</a></li>
			<li><a rel="external" href="https://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html">Writing Efficient JavaScript: Chapter 7 - Even Faster Websites</a></li>
		</ul>
	</section>
</section>

<section>
	<h2>CSS code optimization</h2>
	<ul>
		<li><strong>Minimize class names:</strong> CSS class names are often reused multiple times within CSS and HTML files so can quickly add bulk to files if they are unnecessarily long. Keep class names as short as possible while ensuring they remain unique. A recent WET core framework class name shortening exercise resulted in a 10% to 30% decrease in file sizes.</li>
	</ul>

	<section>
		<h3>Additional techniques</h3>
		<ul>
			<li><a rel="external" href="https://www.queness.com/post/588/15-ways-to-optimize-css-and-reduce-css-file-size">15 Ways to Optimize CSS and Reduce CSS File Size</a></li>
			<li><a rel="external" href="https://web.archive.org/web/20190119144722/http://www.dailycoding.com/Posts/top_7_tip_for_optimizing_css.aspx">Top 7 Tip for Optimizing CSS</a></li>
			<li><a rel="external" href="https://perishablepress.com/how-to-micro-optimize-your-css/">How to Micro-Optimize Your CSS]</a></li>
		</ul>
	</section>
</section>

<section>
	<h2>HTML code optimization</h2>
	<ul>
		<li><strong>Minimize the use of HTML comments:</strong> Every kilobyte counts when it comes to mobile devices so avoid unnecessarily bloating your code with HTML comments. Keep comments to the bare minimum by eliminating unnecessary comments and shortening the rest.</li>
		<li><strong>Remove commented out code:</strong> Commented out code should not be left in production Web pages. Commented out code can easily add many unnecessary kilobytes to downloads. Keep unused code separate from production Web pages.</li>
		<li><strong>Use tabs instead of spaces to indent code:</strong> It can take an average of 5 space characters to equal the indent of 1 tab character. Significant file size savings can be achieved by using tabs instead of spaces. Many editing tools provide the ability to quickly switch to indenting with tabs.</li>
		<li><strong>Minimize indenting:</strong> Indenting is helpful for code clarity but can quickly add to the HTML file size. Find a good balance between code clarity and file size to minimize the impact on the end user.</li>
		<li><strong>Remove the <code>type</code> attribute from <code>script</code> elements:</strong> In HTML5, <code>type="text/javascript"</code> is no longer required on <code>script</code> elements. Only use the <code>type</code> attribute on <code>script</code> elements for non-JavaScript scenarios.</li>
		<li><strong>Remove the <code>type</code> attribute from <code>style</code> elements:</strong> In HTML5, <code>type="text/css"</code> is no longer required on style elements. Only use the <code>type</code> attribute on <code>style</code> elements for non-CSS scenarios.</li>
	</ul>
</section>

<section>
	<h2>Web server optimization</h2>
	<ul>
		<li>Enable Gzip compression on your Web server. Gzip compression can reduce file transfer sizes by up to 70%. ''Note:''' Gzip compression does not reduce the impact on end user cache sizes (cached uncompressed) so files sizes should be reduced as much as possible before Gzip compression.</li>
	</ul>
</section>
