John Lawrimore, 2014 JavaScript Performance Presenter JOHN - Principal Consultant at.

Slides:



Advertisements
Similar presentations
JavaScript & jQuery JavaScript and jQuery introduction.
Advertisements

The jQuery library. What is jQuery ? A javascript lightweight library Is very easy to use Is powerful Is cross-browser compatible Downloadable from jQuery.com,
The Document Object Model (DOM) 1 JavaScript is an object-based language—that is, it’s based on manipulating objects by changing each object’s properties.
JQuery CS 380: Web Programming. What is jQuery? jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling,
HTML 5 and CSS 3, Illustrated Complete Unit L: Programming Web Pages with JavaScript.
Lesson 12- Unit L Programming Web Pages with JavaScript.
XHTML & CSS 2 By Trevor Adams. Last week XHTML eXtensible HyperText Mark-up Language The beginning – HTML Web Standards Concept and syntax Elements (tags)
Chapter 16 Dynamic HTML and Animation The Web Warrior Guide to Web Design Technologies.
Working with Cascading Style Sheets. 2 Objectives Introducing Cascading Style Sheets Using Inline Styles Using Embedded Styles Using an External Style.
Philly.NET Hands-On jQuery + Plug-ins Bill Wolff, Rob Keiser.
1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)
DHTML - Introduction Introduction to DHTML, the DOM, JS review.
XP Tutorial 7New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with Cascading Style Sheets Creating a Style for Online Scrapbooks.
What makes browsers performant Christian Stockwell Microsoft Corporation.
HTML DOM.  The HTML DOM defines a standard way for accessing and manipulating HTML documents.  The DOM presents an HTML document as a tree- structure.
JQuery 10/21. Today jQuery Some cool tools around the web JavaScript Libraries Drawing libraries HTML Frameworks Conventions.
Cascading Style Sheets. Defines the presentation of one or more web pages Similar to a template Can control the appearance of an entire web site giving.
SYST Web Technologies SYST Web Technologies Lesson 6 – Intro to JavaScript.
Execution Environment for JavaScript " Java Script Window object represents the window in which the browser displays documents. " The Window object provides.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
DOM and JavaScript Aryo Pinandito.
JQuery Adding behaviour…. Lecture Plan Review of last lesson Adding behaviour –click, mouseover Animation –fade, slideDown Navigation –parent, find, next.
JQUERY | INTRODUCTION. jQuery  Open source JavaScript library  Simplifies the interactions between  HTML document, or the Document Object Model (DOM),
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
JavaScript – The DOM JavaScript is object based The browser is object based – We can access the browser's objects in the same way we did JavaScript's Two.
JavaScript, Fourth Edition
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
5.2 DOM (Document Object Model). 2 Motto: To write it, it took three months; to conceive it three minutes; to collect the data in it — all my life. —F.
Embedded Software SKKU 28 1 WebKit/EFL. Embedded Software SKKU 28 2 WebKit Parsing Layout and Painting WebKit and EFL Contents.
INTRODUCTION TO HTML5 Using jQuery with HTML5. Introducing jQuery  Although it is not a part of any W3C or WHATWG specification, jQuery performs an important.
Javascript II DOM & JSON. In an effort to create increasingly interactive experiences on the web, programmers wanted access to the functionality of browsers.
JQuery Performance Tips Eric Presentation files: goo.gl/i6UbB.
Unleash the Power of jQuery Doncho Minkov Telerik Software Academy academy.telerik.com Senior Technical Trainer
Web Development 101 Presented by John Valance
JQuery Introduction © Copyright 2014, Fred McClurg All Rights Reserved.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.2 Revised by Dr. T. Tran for CSI3140.
PERFORMANCE ENHANCEMENT IN ASP.NET By Hassan Tariq Session #1.
JavaScript, Fourth Edition
Unleash the Power of jQuery Learning & Development Team Telerik Software Academy.
1 Javascript DOM Peter Atkinson. 2 Objectives Understand the nature and structure of the DOM Add and remove content from the page Access and change element.
JQuery JavaScript is a powerful language but it is not always easy to work with. jQuery is a JavaScript library that helps with: – HTML document traversal.
Modifying HTML attributes and CSS values. Learning Objectives By the end of this lecture, you should be able to: – Select based on a class (as opposed.
CNIT 132 – Week 4 Cascading Style Sheets. Introducing Cascading Style Sheets Style sheets are files or forms that describe the layout and appearance of.
JQuery Overview Unleash the Power of jQuery SoftUni Team Technical Trainers Software University
Intro to jQuery. What is jQuery? A JavaScript library Lightweight (about 31KB for the minified version) Simplifies HTML document traversing (DOM), event.
Unit 13 –JQuery Basics Instructor: Brent Presley.
Introduction to jQuery. 2 Objectives When you complete this chapter, you will be able to: Select elements using jQuery syntax Use built-in jQuery functions.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
Web Technologies Lecture 8 JQuery. “A fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax.
JavaScript Introduction and Background. 2 Web languages Three formal languages HTML JavaScript CSS Three different tasks Document description Client-side.
Advanced CSS. Display  Hiding an element can be done in two ways  display:none  Element is hidden and will no longer take up space on the page  Can.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
CSE 154 LECTURE 9: THE DOM TREE. The DOM tree The elements of a page are nested into a tree-like structure of objects the DOM has properties and methods.
1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)
XP Tutorial 7New Perspectives on HTML and XHTML, Comprehensive 1 Working with Cascading Style Sheets Creating a Style for Online Scrapbooks Tutorial 7.
Working with Cascading Style Sheets
Programming Web Pages with JavaScript
Unit M Programming Web Pages with
Unleash the Power of jQuery
Unit M Programming Web Pages with
CGS 3066: Web Programming and Design Spring 2017
Introduction to JavaScript
JavaScript Introduction
A second look at JavaScript
jQuery The Easy JavaScript Nikolay Chochev Technical Trainer
Introduction to JavaScript
JavaScript CS 4640 Programming Languages for Web Applications
Ajax and JSON Jeremy Shafer Department of MIS Fox School of Business
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

John Lawrimore, 2014 JavaScript Performance

Presenter JOHN - Principal Consultant at Improving Enterprises - Microsoft enthusiast - Background heavy in web applications development - Unable to think of interesting things to say about self

Access this Presentation Online

Objectives 1.Provide a better understanding of how JavaScript works 2.Introduce practices and techniques that will noticeably increase performance 3.Focus ONLY on what... Generally applies to all browsers You can reasonably begin implementing tomorrow

Approaching Optimization The right optimization strategy will differ by application Do what makes sense Pick your battles Consider maintainability Challenge your assumptions regularly

What is scope chain?

Scope Chain

Namespacing Condenses the global namespace Reduces search time for its descendants HINT: Set distant namespaces to a variable to reduce search time

Closures (anonymous functions) Pros: Access to variables outside the function Cons: Adds to the scope chain Requires a new execution context

What’s wrong with this?

With and Try-Catch Use Try-Catch sparingly And NEVER try catch in a loop! NEVER use With !

What’s missing?

Local variables missing the var keyword are automatically instantiated in the global namespace!! ! What’s missing?

Managing Scope Don’t use the global namespace! Cache out-of-scope variables referenced more than once Limit augmentations to the scope chain Closures With Try Catch Consider scope when creating prototypes Don’t forget to use ‘var’

What is the DOM?

Document Object Model

Under the hood

What impacts DOM performance?

DOM Performance Issues DOM search DOM manipulation !!

What’s wrong with this?

THE DOM IS NOT A DATABASE! ! What’s wrong with this?

Data Property Maintained within the JavaScript engine (not the DOM) Can be global or bound to a specific element

Data vs. Attributes Attribute StorageData Property Avoids hits to the DOM Accommodates types, arrays and complex objects Optimized by built-in caching Maintains valid HTML

Data vs. Attributes

What is Reflow/Repaint?

Repaint vs. Reflow REPAINT Visual changes that do not alter the document layout. (aka: redraw) Examples: Color Font style REFLOW Occurs when a visual change is made to the HTML document that requires layout to be computed. Examples: Initial render Browser window resize Visible elements added or removed Element position changes Changes in size, margin, border, etc. Text changes Layout information is retrieved (in some cases)

Repaint vs. Reflow Both are expensive in terms of performance because they require traversing Reflow may or may not affect the entire document JavaScript engines attempt to perform reflow in batches

Let’s improve this!

DocumentFragment Child of the document that created it No visual representation Construct happens behind the scenes When passed to appended to document, only its children are added

CSS Transitions > Animation Allows property changes in CSS values to occur smoothly over a specified duration. Powerful, clean, and faster than JS animations Not supported in IE 9 and earlier

Avoiding Reflow Group styles whenever possible Use classes or cssText instead of styles Accumulate new elements and append with one call innerHTML (or html() for jQuery) documentFragment Temporarily remove elements to be modified from the document remove(), detach(), etc. Avoid animation, and leverage libraries or CSS transitions when you must

What is the outcome of this method?

IT NEVER ENDS! !

HtmlCollections Don’t let them fool you! They are not arrays! Examples: document.getElementsByTagName document.getElemenetsByClassName document.images document.forms

Let’s improve this!

Only touch the HTMLCollection one time

Reducing DOM Interaction Never store data on the DOM Avoid reflow Limit calls to HtmlCollections

UI Thread Responsibilities Draw UI Execute JavaScript ! UI THREAD CAN ONLY DO ONE RESPONSIBILITY AT A TIME

Timers Run secondary tasks in the back ground AFTER the page has loaded. When timer is done, job is added to the UI Queue. Remember that less timers with more work is better than more timers with less work.

Web Workers New option for asynchronous execution in HTML5 Operates outside of UI Thread Trigger specified event handlers when completed

What loop should I use?

Loops for for-in for-each [].forEach() $().each() do-while while

Selecting a Loop Avoid non-native function based loops Creates closures (and associated overhead) in scope chain Takes about 8-10x as long as basic for loop Avoid for-in and for-each for-in performs expensive type evaluation for-each deprecated in ECMA -357

Selecting a Loop What matters? Amount of work being performed Number of iterations Do Less Work!! Avoid lookups inside loop Reduce number of calculation being performed

How can this be improved?

Combine control condition and control variable into a single statement How can this be improved? BETTER!

Combine the terminal condition evaluation w/ incrementing / decrementing How can this be improved? BETTER! BEST!

Switch or If-Then-Else?

Selecting a Conditional Statement It Depends! As conditions increase, switch becomes more and more optimal

Let’s improve this!

BETTER! Consider a combined approach!

Let’s improve this! BETTER! Create a hash table OR EVEN

Common Pitfalls

What’s wrong here?

MEMORY LEAK! !

What’s wrong here? MEMORY LEAK! ! Break the chain!

What’s wrong here?

WILL BE CALLED WAY TOO MUCH! !

Throttle and Debounce Throttling limits the execution of a function to no more than once every delay milliseconds Debouncing guarantees that the function will only ever be executed a single time (given a specified threshold).

Smarter Coding

Which is better?

BETTER! Use literals, avoid ‘new’

Which way is better?

Use prototypes!

Reuse/Recycle Reuse old variables instead of creating new ones!

Event Delegation Handle array element events with a single binding on the container Events to bubble up the DOM tree Detect the node originating the event and act accordingly Use stopPropagation(), preventDefaults(), etc. as needed

Let’s improve this!

BETTER! Use lazy loading

String Manipulation Use += over function based concatenation Use regexes to parse and slice

Which is faster?

BETTER! Use bitwise operators where appropriate

Traversing Always use the most optimum methods for crawling the DOM DOM properties such as childNode, firstChild, nextSibling, etc. don’t distinguish between element and other node types (such as spaces, comments, etc.)

JSON eval()  SLOW! Libraries  EVEN WORSE! Always use the JSON namespace Native in all modern browsers (IE8+) JSON.parse() JSON.stringify() toJSON() prototype !

Are libraries efficient?

Using Libraries The most optimal library is no match to the JavaScript Engine! Intermediaries come with overhead Native methods are compiled machine code Leverage libraries only in cases where value is added…

Use native features over libraries indexOf() lastIndexOf() every() filter() forEach() map() some()

querySelectorAll() Much faster than using JavaScript and DOM to iterate and narrow down a list of elements Supported in IE8+

What selector should I use?

Selectors All selectors are NOT created equal Always consider what is going on under the covers! TypeExample Universal * Type div ID #header Class.promo Attribute [type=“text”] Pseudo-class a:hover Adjacent sibling h2 + p Child li > ul Descendant ul a

ID & Element Selectors $(‘#Element, form, input’) Most optimal choice! Backed by native DOM operations eg. getElementById()

Class Selectors $(‘.element’) Much slower selector Particularly in browsers where getElementsByClassName() is not supported !

Pseudo & Attribute $(‘:visible, :hidden’); $(‘[attribute=value]’); USE SPARINGLY No native calls available querySelector() and querySelectorAll() help in modern browsers !

Combining Selectors Selector engines use the Right to Left Model Always make your MOST SPECIFIC selector on the right

Let’s rank these! A. $('.child', $('#parent')) B. $(‘#parent >.child’) C. $parent.find(‘.child’) D. $(‘#parent.child’) E. $(‘.child’, $parent) F. $parent.children(".child’)

Let’s rank these! D. $(‘#parent.child’) B. $(‘#parent >.child’) F. $parent.children(".child’) A. $('.child', $('#parent')) E. $(‘.child’, $parent) C. $parent.find(‘.child’) RESULTS:

Can Script Tags Hurt Performance?

Script Tags PROBLEMS External references result in an http request Inline scripts circumvent client-side caching

Load Script Tags Faster ALWAYS "minify" production code! Bundle scripts (and styles) into single resources Leverage Code Delivery Networks (CDN) Lazy load scripts with AMD utilities

AMD Asynchronous Module Definition Example: require.js

How do I Test Performance?

jsPerf Compare the performance of code snippets across browsers

YSlow Grade your site’s optimizations

Reading Material High Performance JavaScript Nicholas C. Zakas

Questions?