1. Trang chủ
  2. » Công Nghệ Thông Tin

ajax-perf.ppt

42 524 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề High Performance Ajax Applications
Tác giả Julien Lecomte
Trường học Not Available
Chuyên ngành High Performance Ajax Applications
Thể loại Bài viết
Năm xuất bản 2025
Thành phố Not Available
Định dạng
Số trang 42
Dung lượng 646,5 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Ajax performance

Trang 1

High Performance Ajax Applications

Julien Lecomte

http://www.julienlecomte.net/blogfiles/performance/ajax-perf.ppt

http://www.slideshare.net/julien.lecomte/high-performance-ajax-applications

Trang 2

Part 1 Developing For High Performance

Trang 3

Planning and designing for high performance

• Plan for performance from day 1

• Work closely with designers and product managers

• Understand design rationale

• Explain the tradeoffs between design and performance

• Offer alternatives and show what is possible (prototype)

• Challenge yourself to implement challenging designs (don't just say no)

• Help simplify the design and interaction if needed (compromise)

Trang 4

Engineering high performance:

A few basic rules

• Less is more

– Don’t do anything unnecessary.

– Don’t do anything until it becomes absolutely necessary.

• Break the rules

– Make compromises and break best practices, but only as a last resort!

• Work on improving perceived performance

– Users can deal with some reasonable amount of slowness if:

• They are informed appropriately that an operation is pending.

• The user interface remains reactive at all time.

– Cheat whenever you can by first updating the UI and then do the work.

• Need to “lock” all or part of the user interface.

Trang 5

Measuring performance

• Test performance using a setup similar to your users’ environment

• Profile your code during development

• Automate profiling/performance testing

• Keep historical records of how features perform

• Consider keeping some (small amount of) profiling code in production

Trang 6

Part 2 High Performance

Page Load

Trang 7

Yahoo!'s Exceptional Performance rules

1 Make Fewer HTTP Requests

2 Use a Content Delivery Network

3 Add an Expires Header

4 Gzip Components (including JS!)

5 Put CSS at the Top

6 Move Scripts to the Bottom

14 Make Ajax Cacheable

See http://developer.yahoo.com/performance/ for more information.

• A web page works in 3 (sometimes imbricated) stages:

1) load 2) render 3) run

These rules cover mostly the first stage.

• A web page works in 3 (sometimes imbricated) stages:

1) load 2) render 3) run

These rules cover mostly the first stage.

Trang 8

Asset optimization

• Minify CSS and JavaScript files:

– Use the YUI Compressor [ http://developer.yahoo.com/yui/compressor/ ]– Stay away from so-called advanced compression schemes - like Packer

• Combine CSS and JavaScript files:

– At build time [ http://www.julienlecomte.net/blog/2007/09/16/ ]

Trang 9

Reduce unminified code size

• Loading and parsing HTML, CSS and JavaScript code is costly.

• Be concise and write less code.

• Make good use of JavaScript libraries.

• Consider splitting your large JavaScript files into smaller files (bundles) when the parsing and compilation of the script takes an excessive amount of time (Firefox bug #313967)

• Load code (HTML, CSS and JavaScript) on demand (a.k.a “lazy loading”)

– See http://ajaxpatterns.org/On-Demand_Javascript

– Use the YUI Loader

– Dojo's package system

– JSAN Import System

Trang 10

Optimize initial rendering (1/4) Miscellaneous tips

• Consider rendering the first view on the server:

– Be aware of the added page weight

– You will still need to attach event handlers once the DOM is ready

• Close Your HTML Tags to Speed Up Parsing:

– Implicitly closed tags add cost to HTML parsing

– http://msdn2.microsoft.com/en-us/library/ms533020.aspx#Close_Your_Tags

• Consider flushing the apache buffer very early on:

– The download of external CSS files (should be at the top of the page!) may get a head start.– May not influence the rendering speed however Browsers buffer their input before displaying it.

• Load only essential assets / load assets on a delay or on demand

– Use the YUI Image Loader

Trang 11

Optimize initial rendering (2/4) Don’t always wait for onload

• Most DOM operations can be accomplished before the onload event has fired.

• If you have control over where your code is going to be inserted in the page, write your init code in a <script> block located right before the closing </body> tag

• Otherwise, use the YUI Event utility’s onDOMReady method:

// Do something here

// e.g., attach event handlers.

});

Trang 12

Optimize initial rendering (3/4) Post-load script loading

• A well designed site should be fully functional, even without JavaScript enabled.

• Therefore, you may be able to load scripts on a delay.

• Doing so benefits the loading of other assets (style sheets, images, etc.)

• Which makes your site load faster

• Right before the closing </body> tag, insert the following:

<script>

window.onload = function () { var script =

Trang 13

Optimize initial rendering (4/4) Conditional preloading

• Preloading assets (JavaScript, CSS, Images, etc.) has the potential to really enhance the user experience

• However, one must be smart about when the preloading takes place Otherwise, the preloading may actually worsen the user experience

• http://www.sitepoint.com/article/web-site-optimization-steps/3

• Try it at http://search.yahoo.com/

Trang 14

Part 3 High Performance

JavaScript

Trang 15

Reduce the amount of symbolic look-up: The scope chain (1/2)

var g = 7;

function f(a) {

var v = 8;

x = v + a + g; }

f(6);

var g = 7 ;

function f(a) { var v = 8 ;

x = v + a + g; }

f(6);

parent

• Look-up is performed every time a variable is accessed.

• Variables are resolved backwards from most specific to least specific scope.

Trang 16

Reduce the amount of symbolic look-up: The scope chain (2/2)

• Therefore, declare (with the var keyword) and use variables in the same scope

whenever possible, and avoid global variables at all costs

• Never use the with keyword, as it prevents the compiler from generating code for fast access to local variables (traverse the object prototype chain first, and then up the scope chain, and so on)

• Cache the result of expensive look-ups in local variables:

l = arr.length;

localVar = globalVar;

for (i = 0; i < l; i++) { localVar++;

} globalVar = localVar;

})();

var arr = ;

var globalVar = 0 ; (function () {

var i, l, localVar;

l = arr.length;

localVar = globalVar;

for (i = 0 ; i < l; i++) { localVar++;

} globalVar = localVar;

})();

(faster on all A-grade browsers)

Trang 17

Reduce the amount of symbolic look-up: The prototype chain

Trang 18

Optimize object instantiation

• If you need to create many objects, consider adding members to the prototype instead

of adding them to each individual object in the object constructor (properties are bound once, to the prototype object)

• This also reduces memory consumption.

• However, it slows down the look-up of object members.

Trang 19

Don’t use eval!

• The string passed to eval (and its relatives, the Function constructor and the

setTimeout and setInterval functions) needs to be compiled and interpreted Extremely slow!

• Never pass a string to the setTimeout and setInterval functions Instead, pass

an anonymous function like so:

setTimeout(function () {

// Code to execute on a timeout

}, 50);

setTimeout(function () { // Code to execute on a timeout

}, 50 );

• Never use eval and the Function constructor (except in some extremely rare cases, and only in code blocks where performance is not critical)

Trang 20

Optimize string concatenation

• On Internet Explorer (JScript), concatenating two strings causes a new string to be

allocated, and the two original strings to be copied:

}

s = s.join(“”);

var i, s = [];

for (i = 0 ; i < 10000 ; i++) { s[i] = “x” ;

Trang 21

Optimize regular expressions

• Don’t use the RegExp constructor, unless your regular expression is assembled at runtime Instead, use regular expression literals

• Use the test method if all you want to do is test for a pattern (the exec method carries a small performance penalty)

• Use non-capturing groups (?: )

• Stick to simple patterns If your regular expression looks like the following, reconsider

if (/loaded|complete/.test(document.readyState)) { }

if ( /loaded|complete/ test(document.readyState)) { }

(?:(?:\r\n)?[\t])*(?:(?:(?:[^()<>@,;:\\".\[\]\000-\031]+(?:(?:(?:\r\n)?[\t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|" (?:[^\"\r\\]|\\.|(?:(?:\r\n)?[\t]))*"(?:(?:\r\n)?[\t])*)(?:\.(?:(?:\r\n)?[\t])*(?:[^()<>@,;:\\".\[\]\000-\031 ]+(?:(?:(?:\r\n)?[\t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[\t]))*"(?:(?:\r\n)?[\t])

*))*@(?:(?:\r\n)?[\t])*(?:[^()<>@,;:\\".\[\]\000-\031]+(?:(?:(?:\r\n)?[\t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[ ([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[\t])*)(?:\.(?:(?:\r\n)?[\t])*(?:[^()<>@,;:\\".\[\]\000-\031]+(?:(?:(?:\r\n)? [\t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[\t])*))*|(?:[^()<>@,;:\\".\[\]\000-\0 31]+(?:(?:(?:\r\n)?[\t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[\t]))*"(?:(?:\r\n)?[\t ])*)*\<(?:(?:\r\n)?[\t])*(?:@(?:[^()<>@,;:\\".\[\]\000-\031]+(?:(?:(?:\r\n)?[\t])+|\Z|(?=[\["()<>@,;:\\".\[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\.)*\](?:(?:\r\n)?[\t])*)(?:\.(?:(?:\r\n)?[\t])*(?:[^()<>@,;:\\".\[\]\000-\031]+(?:(?:(?:

\r\n)?[\t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[\t])*))*(?:,@(?:(?:\r\n)?[\t]))

Trang 22

• Caching can be justified by:

– High cost (CPU or network latency) associated with getting a value

– Value will be read many times

– And will not change often!

• Increases memory consumption  tradeoff

fn.b = true;

} return fn.v;

}

function fn () {

if (!fn.b) { fn.v = ;

fn.b = true ; }

return fn.v;

}

var fn = function () { var v = ;

return (fn = function () { return v;

})();

};

var fn = function () { var v = ;

return (fn = function () { return v;

})();

};

Trang 23

How to handle long running JavaScript processes (1/2)

• During long running JavaScript processes, the entire browser UI is frozen

• Therefore, to maintain a decent user experience, make sure that JavaScript threads never take more than ~ 300 msec (at most) to complete

• You can break long running processes into smaller units of work, and chain them using setTimeout

• You can also process the data on the server.

• More info at http://www.julienlecomte.net/blog/2007/10/28

• Demo

Trang 24

How to handle long running JavaScript processes (2/2)

function doSomething (callbackFn) {

// Initialize a few things here

function doSomething (callbackFn) {

// Initialize a few things here

Trang 25

} } catch (e) {

}

myArray.push(value);

myArray[myArray.length] = value; myArray[idx++] = value;

myArray.push(value);

myArray[myArray.length] = value; myArray[idx++] = value;

Trang 26

Miscellaneous tips (2/2)

• If possible, avoid for in in performance-critical sections:

var key, value;

for (key in myArray) {

value = myArray[key];

}

var key, value;

for (key in myArray) {

Trang 27

Part 4 High Performance Dynamic HTML

Trang 28

Document tree modification Using innerHTML

var i, j, el, table, tbody, row, cell;

for (j = 0; j < 5; j++) { html[idx++] = "<td></td>"; }

html[idx++] = "</tr>";

} html[idx++] = "</table>";

el = document.createElement("div"); document.body.appendChild(el);

el.innerHTML = html.join("");

var i, j, el, idx, html;

idx = 0 ; html = [];

html[idx++] = "<table>" ;

for (i = 0 ; i < 1000 ; i++) { html[idx++] = "<tr>" ; for (j = 0 ; j < 5 ; j++) { html[idx++] = "<td></td>" ; }

html[idx++] = "</tr>" ; }

html[idx++] = "</table>" ;

el = document.createElement( "div" ); document.body.appendChild(el);

el.innerHTML = html.join( "" );

(much faster on all A-grade browsers)

Warning: See http://www.julienlecomte.net/blog/2007/12/38/

Trang 29

Document tree modification Using cloneNode

var i, j, el, table, tbody, row, cell;

tbody = document.createElement("tbody"); table.appendChild(tbody);

template = document.createElement("tr");

for (i = 0; i < 5; i++) {

cell = document.createElement("td"); template.appendChild(cell);

}

for (i = 0 ; i < 1000 ; i++) { row = template.cloneNode(true);

tbody.appendChild(row);

}

(faster on all A-grade browsers – sometimes much faster)

Warning: expando properties/attached event handlers are lost!

Trang 30

Document tree modification Using DocumentFragment

• A DocumentFragment (DOM Level 1 Core) is a lightweight Document object.

• It supports only a subset of the regular DOM methods and properties.

• IE’s implementation of the DocumentFragment interface does not comply with the W3C specification and returns a regular Document object

var i, j, el, table, tbody, row, cell, docFragment;

var i, j, el, table, tbody, row, cell, docFragment;

} document.body.appendChild(docFragment);

Trang 31

Limit the number of event handlers (1/2)

• Attaching an event handler to hundreds of elements is very costly

• Multiplying event handlers augments the potential for memory leaks

Solution: Use event delegation, a technique that relies on event bubbling

Trang 32

Limit the number of event handlers (2/2)

YAHOO.util.Event.addListener("container", "click", function

Trang 33

Limiting reflows

• Reflows happen whenever the DOM tree is manipulated.

• Browsers have optimizations you may take advantage of to minimize reflow:

– Modifying an invisible element (display:none) does not trigger reflow

– Modifying an element “off-DOM” does not trigger reflow

• Batch style changes:

– Change the value of the style attribute using setAttribute (does not work on Internet Explorer) Example:

– Change the value of the cssText property of the style object Example:

– More maintainable: Change the CSS class name of an element Example:

el.style.cssText = "display:block;width:auto;height:100px; ";

el.style.cssText = "display:block;width:auto;height:100px; " ;

YAHOO.util.Dom.replaceClass(el, "foo", "bar");

YAHOO.util.Dom.replaceClass(el, "foo" , "bar" );

el.setAttribute("style", "display:block;width:auto;height:100px; ");

el.setAttribute( "style" , "display:block;width:auto;height:100px; " );

Ngày đăng: 13/08/2012, 22:49

Xem thêm

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w