SlideShare a Scribd company logo
1 of 72
Embracing YUI 3 & Frontend Performance Morgan Cheng, Jan 6th 2011
YUI 3 Lighter Faster Easier to use
YUI 2 to YUI 3
YUI 2 sample module  YAHOO.namespace(‘MyProject’); (function() { var MODULE_NAME=“MyProject”,        Dom = YAHOO.util.Dom; YAHOO.MyProject.MyDialog = function() {       . . .    }; }());
Another YUI 2 sample module YAHOO.namespace(‘MyProject’); (function() { var MODULE_NAME=“MyProject”,        Dom = YAHOO.util.Dom        Event = YAHOO.util.Event; YAHOO.MyProject.MyPage = {       init: function() {       },       . . .         }; Event.onDOMReady(YAHOO.MyProject.MyPage.init, null, YAHOO.MyProject.MyPage); }());
Not Enough for Mash-up Page
Limitation YAHOO property can be overwritten… YAHOO.widget.HelloWorld = something; // by one developer … YAHOO.widget.HelloWorld = another; // by another developer
YUI 3 module YUI.add(“myModule”, function(Y) { Y.namespace(‘myproject’).mod = function() {       };    },     “0.0.1”,                            //module version    {requires: [‘node’]}       // dependecies );
Use YUI 3 module YUI().use(“myModule”,  function(Y) { varm = new Y.myProject.mod;    . . . }); This might be easy to read: varyui = YUI(); yui. use(“myModule”, function(Y) { varm = new Y.myProject.mod;    . . . });
Sandboxing YUI().use(“myModule”,  function(Y) { varm = new Y.myProject.mod; }); YUI().use(“node”,  function(Y) {    //no myProject for this Y });
DOM <div id=“menu”> 	  <h1>B1 Canteen Menu</h1>       <ul>              <li>Fish</li>              <li class=“promotion”>Noodle</li>              <li class=“promotion”>Meat</li>              <li>Rice</li>              <li>Tomato</li>       </ul> </div>
In YUI 2 To get <li> element with “promotion” class under element with id “menu” var Dom = YAHOO.util.Dom; var el = Dom.get(‘menu’); varpromotedItems = Dom.getElementsByClassName(‘promotion’, ‘li’, el);
Selector API in YUI 3 One-liner YUI().use(‘node’, function(Y) { varpromtedItems = Y.all(‘#menuli.promotion’); });
Selector Best Practice Prefer “#id” Prefer simple selector over complex selector
YUI 2 Selector Utility http://developer.yahoo.com/yui/selector/ But, not chainable returning raw Dom elements
Node & NodeList Wrapper of DOM elements From function-based to object-based In YUI 2 var el = YAHOO.util.Dom.get(‘id’); YAHOO.util.Dom.addClass(el, ‘className’); In YUI 3 Y.one(‘id’).addClass(‘className’);
YUI 3 Chainable YUI().use(‘node’, function(Y) { Y.all(“#menuli”)        .each(function(node, i, ctx) {                 if ( i % 2) {  node.addClass(‘even’).removeClass(‘disable’);                  }        })        .setStyle(‘color, ‘red’); });
Event Event Facade YUI().use(‘event’, ‘node’, function(Y) { Y.one(‘id’).on(‘click’, function(e) { Y.log(e.currentTarget);           e.preventDefault();      }); });
   Wait, but how does these stuff get loaded into page?
Seed File <script src="http://yui.yahooapis.com/3.2.0/build/yui/yui-min.js"></script> YUI().use(‘node’, function(Y) { });
Seed File with Loader <script type="text/javascript" src="http://yui.yahooapis.com/combo?3.2.0/build/yui/yui-min.js&3.2.0/build/loader/loader-min.js"></script> YUI().use(‘node’, function(Y) { });
Traditional Way <script type="text/javascript" src="http://yui.yahooapis.com/combo?3.2.0/build/yui/yui-min.js&3.2.0/build/loader/loader-min.js&3.2.0/build/oop/oop-min.js&3.2.0/build/dom/dom-min.js&3.2.0/build/dom/dom-style-ie-min.js&3.2.0/build/event-custom/event-custom-base-min.js&3.2.0/build/event/event-base-min.js&3.2.0/build/pluginhost/pluginhost-min.js&3.2.0/build/node/node-min.js&3.2.0/build/event/event-delegate-min.js"></script>
YUI 3 Dependency Magic Ramp-up Combine
JavaScript Blocks
Script Blocks Page Rendering <script type=“text/javascript” src=“long-time.js”></script> <imgsrc=“I-am-bocked.png”></img>
Script Blocks Script <script type=“text/javascript” src=“long-time.js”></script> <script type=“text/javascript” src=“I-am-bocked.js”></script>     post-IE8 browsers do asynchronous downloading
Non-blocking JavaScript defer attribute async attribute iframe document.write XHR injection Commented Javascript JavaScript downloaded as Image & Object …
Dynamic Script Tag function createScript(js) { var script = document.createElement(‘script’); script.type = ‘text/javascript’; script.async = “true”; var head = document.getElementsByTagname(‘head’)[0];   head.appendChild(script); }
Execution Order Matters Execution order is not guaranteed to be preserved for asynchronous script loading YUI 3 is born to solve execution order problem each module payload is not executed until all dependencies are ready
Don’t Get Excited Too Early
Deficiency in YUI 3 Loader YUI().use blocks each other YUI().use(‘node’, function() { 	. . . }); YUI().use(‘event’, function() {     . . . });
Deficiency in YUI 3 Loader Disabling combo makes each module loaded in sequence YUI({     combine: false }).use(‘node’, ‘event’, function() { 	. . . });
Prefetch YUI Loader hack http://bazaar.launchpad.net/~launchpad-pqm/lazr-js/toolchain/annotate/188/src-js/lazrjs/loader/prefetch.js
Flickr Lesson #1 Firewall can cut your long URL         http://yui.yahooapis.com/combo?3.2.0/build/yui/yui-min.js&3.2.0/build/oop/oop-min.js&3.2.0/build/event-custom/event-custom-min.js&3.2.0/build/event/event-base-min.js&3.2.0/build/pluginhost/pluginhost-min.js&3.2.0/build/attribute/attribute-min.js&3.2.0/build/dom/dom-min.js&3.2.0/build/dom/dom-style-ie-min.js&3.2.0/build/node/node-min.js&3.2.0/build/event/event-delegate-min.js&3.2.0/build/base/base-min.js&3.2.0/build/anim/anim-min.js&3.2.0/build/node/align-plugin-min.js&3.2.0/build/classnamemanager/classnamemanager-min.js&3.2.0/build/intl/intl-min.js&3.2.0/build/console/lang/console.js&3.2.0/build/event/event-synthetic-min.js&3.2.0/build/event/event-focus-min.js&3.2.0/build/widget/widget-min.js&3.2.0/build/dump/dump-min.js&3.2.0/build/substitute/substitute-min.js&3.2.0/build/console/console-min.js&3.2.0/build/plugin/plugin-min.js&3.2.0/build/console/console-filters-min.js&3.2.0/build/cookie/cookie-min.js&3.2.0/build/dom/dom-style-ie-min.js&3.2.0/build/event/event-resize-min.js&3.2.0/build/event/event-mouseenter-min.js&3.2.0/build/dd/dd-min.js&3.2.0/build/dd/dd-gestures-min.js&3.2.0/build/dd/dd-drop-plugin-min.js&3.2.0/build/dd/dd-plugin-min.js&3.2.0/build/event/event-touch-min.js&3.2.0/build/event-gestures/event-move-min.js&3.2.0/build/dd/dd-gestures-min.js&3.2.0/build/dataschema/dataschema-base-min.js&3.2.0/build/dataschema/dataschema-array-min.js&3.2.0/build/cache/cache-base-min.js&3.2.0/build/querystring/querystring-stringify-simple-min.js&3.2.0/build/io/io-base-min.js&3.2.0/build/json/json-min.js&3.2.0/build/dataschema/dataschema-json-min.js&3.2.0/build/dataschema/dataschema-text-min.js&3.2.0/build/dataschema/dataschema-xml-min.js&3.2.0/build/datasource/datasource-min.js
Flickr Lesson #2 Sexy URL is not welcome http://… &xxw.js&xxx.js&…
Multiple Pages Page A module A + B + C + D + E + X Page B module A + B + C + D + E + Y Page C module A + B + C + D + Z
YUI 3 in Action
Widget Class Diagram
Code Reuse Y.extend Y.augment Y.clone      	//deep copy by value Y.merge		//mix-in multiple objects Y.aggregate
Powerful Y.mix Y.mix(r, s, ov, wl, mode, merge) mode: 0. object to object 1. prototype to prototype 2. prototype to prototype and object props 3. prototype to object  4. object to prototype
EventTarget publish fire on before after
Attribute set get
Base Initializer destrutor static property NAME as event prefix
Widget render renderUI bindUI syncUI
Plugin Y.namespace('QPlus').DigPlugin = Y.Base.create('Dig', Y.Plugin.Base, [],  {  	//prototypal properties }, {     // static properties });
Plugin Prototypal Properties Initializer destuctor
Plugin Static Properties NS Mandatory Used as host property name to reference plugin
Use Plugin plug Trigger initializer unplug Trigger destructor
AOP in YUI3 doBefore/onHostEvent/doAfter Y.SamplePlugin = Y.Base.create(‘sample’, Y.Plugin.Base, [], { initializer: function() { this.doBefore(‘someMethod’, function() { … } );     } }, {     NS: ‘sample’ } );
Custom Event Application Level De-coupling  Identified by string
YUI 2 Custom Event this.myEvent = new YAHOO.util.CustomEvent(‘myEvent’); this.myEvent.fire(); instance.myEvent.subscribe(doSomething);
YUI 3 Custom Event Y.fire(‘chengguan-coming’, 1, 2, 3); Y.on(‘chengguan-coming’, function(arg1, arg2, arg3) {     . . . });
Advanced Custom Event this.publish(‘myEvent’, {      broadcast: 2,  //broadcast to all YUI instances defaultFn: handler // default event handler } ); this.fire(‘myEvent’); instance.on(‘myEvent’, doSomething);
Consistent Event API instance.on(‘click’, onClick); instance.on(‘myEvent’, doSomething);
Synthetic Event Extend DOM event Y.Event.define(‘flick’, {      on: function(node, subscription, notifier) {      },      detach: function(node, subscription notifier) {       } });
Frontend Performance Improvments
No iframe iframe is slow iframerequires one more HTTP roundtrip iframe makes your application complicated
Flush Early  Flush early and user view result early Flush early and external resources starts downloading early
MVC might hurt your performance Model View Controller
How ySymfony MVC works <head> </head> <body>   <div id=“hd”></div>   <div id=“bd”>     <?php echo $sf_content?>   </div>   <div id=“ft”></div> </body> Lib Action Template
Enable Early Flush in ySymfony Don’t use layout setLayout(false) Fetch partial and flush it in Action getPartial flush Customize web response class to avoid head() after flush()
Don’t <html>     . . . 	<body> 		<div>               <div id=‘hd’></div>               <?php flush(); ?> 		      <? // some browser would not render till getting closing tag ?>               <div id=‘bd’></div>               <?php flush(); ?>               <div id=‘ft’></div> 		</div> 	</body> </html>
Do <html>     . . . 	<body>               <div id=‘hd’></div>               <?php flush(); ?>               <div id=‘bd’></div>               <?php flush(); ?>               <div id=‘ft’></div> 	</body> </html>
JavaScript Loading Strategy
JavaScript Loading Strategy Dynamic Script Tag Concatenate JavaScript into single file with FUSE
Users are Not Patient User might start interact with the page before its JavaScript module is loaded It is not good to not respond to user interaction
Put User Actions into Queue
Event-Binder: A Tale of Two JavaScripts Inline Script Prevent default behavior Show progressive UI Put event into queue External Script Flush events from queue Hide progressive UI Remove former event handler
Just at Scratch Line
YUI 3 Resources http://developer.yahoo.com/yui/3/ http://yuiblog.com/ http://twitter.com/miraglia/yui/members yui-users@yahoo-inc.com
Web Performance Resources http://stevesouders.com/ http://www.perfplanet.com/ Velocity
Thanks

More Related Content

What's hot

Beginning iphone 4_devlopement_chpter7_tab_b
Beginning iphone 4_devlopement_chpter7_tab_bBeginning iphone 4_devlopement_chpter7_tab_b
Beginning iphone 4_devlopement_chpter7_tab_b
Jihoon Kong
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
dmethvin
 
The state of Symfony2 - SymfonyDay 2010
The state of Symfony2 - SymfonyDay 2010The state of Symfony2 - SymfonyDay 2010
The state of Symfony2 - SymfonyDay 2010
Fabien Potencier
 

What's hot (20)

A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
 
Beginning iphone 4_devlopement_chpter7_tab_b
Beginning iphone 4_devlopement_chpter7_tab_bBeginning iphone 4_devlopement_chpter7_tab_b
Beginning iphone 4_devlopement_chpter7_tab_b
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Using Objects to Organize your jQuery Code
Using Objects to Organize your jQuery CodeUsing Objects to Organize your jQuery Code
Using Objects to Organize your jQuery Code
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
 
Jquery Fundamentals
Jquery FundamentalsJquery Fundamentals
Jquery Fundamentals
 
Drupal, meet Assetic
Drupal, meet AsseticDrupal, meet Assetic
Drupal, meet Assetic
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
Formacion en movilidad: Conceptos de desarrollo en iOS (III)
Formacion en movilidad: Conceptos de desarrollo en iOS (III) Formacion en movilidad: Conceptos de desarrollo en iOS (III)
Formacion en movilidad: Conceptos de desarrollo en iOS (III)
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
 
Matters of State
Matters of StateMatters of State
Matters of State
 
Love and Loss: A Symfony Security Play
Love and Loss: A Symfony Security PlayLove and Loss: A Symfony Security Play
Love and Loss: A Symfony Security Play
 
The state of Symfony2 - SymfonyDay 2010
The state of Symfony2 - SymfonyDay 2010The state of Symfony2 - SymfonyDay 2010
The state of Symfony2 - SymfonyDay 2010
 
Intro programacion funcional
Intro programacion funcionalIntro programacion funcional
Intro programacion funcional
 
jQuery Namespace Pattern
jQuery Namespace PatternjQuery Namespace Pattern
jQuery Namespace Pattern
 
International News | World News
International News | World NewsInternational News | World News
International News | World News
 
Simple Photo Processing and Web Display with Perl
Simple Photo Processing and Web Display with PerlSimple Photo Processing and Web Display with Perl
Simple Photo Processing and Web Display with Perl
 
BEAR DI
BEAR DIBEAR DI
BEAR DI
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 

Viewers also liked

Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
 
YUI vs jQuery: to Build Large Scale JavaScript App
YUI vs jQuery: to Build Large Scale JavaScript AppYUI vs jQuery: to Build Large Scale JavaScript App
YUI vs jQuery: to Build Large Scale JavaScript App
Morgan Cheng
 
Optimize URL for Performance
Optimize URL for PerformanceOptimize URL for Performance
Optimize URL for Performance
Morgan Cheng
 

Viewers also liked (10)

Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 
F2E's Creeds
F2E's CreedsF2E's Creeds
F2E's Creeds
 
Engineering excellence 卓越工程
Engineering excellence 卓越工程Engineering excellence 卓越工程
Engineering excellence 卓越工程
 
Mobile Web on Touch Event and YUI
Mobile Web on Touch Event and YUIMobile Web on Touch Event and YUI
Mobile Web on Touch Event and YUI
 
YUI vs jQuery: to Build Large Scale JavaScript App
YUI vs jQuery: to Build Large Scale JavaScript AppYUI vs jQuery: to Build Large Scale JavaScript App
YUI vs jQuery: to Build Large Scale JavaScript App
 
Optimize URL for Performance
Optimize URL for PerformanceOptimize URL for Performance
Optimize URL for Performance
 
Comet / WebSocket Web Applications
Comet / WebSocket Web ApplicationsComet / WebSocket Web Applications
Comet / WebSocket Web Applications
 
Comet: an Overview and a New Solution Called Jabbify
Comet: an Overview and a New Solution Called JabbifyComet: an Overview and a New Solution Called Jabbify
Comet: an Overview and a New Solution Called Jabbify
 
JS-Everywhere - SSE Hands-on
JS-Everywhere - SSE Hands-onJS-Everywhere - SSE Hands-on
JS-Everywhere - SSE Hands-on
 
Comet Server Push Over Web
Comet Server Push Over WebComet Server Push Over Web
Comet Server Push Over Web
 

Similar to Embracing YUI3 and Frontend Perf

夜宴52期《从函数构造到YUI沙箱》
夜宴52期《从函数构造到YUI沙箱》夜宴52期《从函数构造到YUI沙箱》
夜宴52期《从函数构造到YUI沙箱》
Koubei Banquet
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUI
Adam Lu
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
Open social 2.0 sandbox ee and breaking out of the gadget box
Open social 2.0 sandbox  ee and breaking out of the gadget boxOpen social 2.0 sandbox  ee and breaking out of the gadget box
Open social 2.0 sandbox ee and breaking out of the gadget box
Ryan Baxter
 
Yui3在美团 2
Yui3在美团 2Yui3在美团 2
Yui3在美团 2
Kai Cui
 
jQuery : Events are where it happens!
jQuery : Events are where it happens!jQuery : Events are where it happens!
jQuery : Events are where it happens!
Wildan Maulana
 

Similar to Embracing YUI3 and Frontend Perf (20)

2009 Hackday Taiwan Yui
2009 Hackday Taiwan Yui2009 Hackday Taiwan Yui
2009 Hackday Taiwan Yui
 
YUI 3
YUI 3YUI 3
YUI 3
 
YUI on the go
YUI on the goYUI on the go
YUI on the go
 
夜宴52期《从函数构造到YUI沙箱》
夜宴52期《从函数构造到YUI沙箱》夜宴52期《从函数构造到YUI沙箱》
夜宴52期《从函数构造到YUI沙箱》
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUI
 
YDN KR Tech Talk : YUI 3.0
YDN KR Tech Talk : YUI 3.0YDN KR Tech Talk : YUI 3.0
YDN KR Tech Talk : YUI 3.0
 
jQuery Internals + Cool Stuff
jQuery Internals + Cool StuffjQuery Internals + Cool Stuff
jQuery Internals + Cool Stuff
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
Yui intro
Yui introYui intro
Yui intro
 
Open social 2.0 sandbox ee and breaking out of the gadget box
Open social 2.0 sandbox  ee and breaking out of the gadget boxOpen social 2.0 sandbox  ee and breaking out of the gadget box
Open social 2.0 sandbox ee and breaking out of the gadget box
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern
 
Yui3在美团 2
Yui3在美团 2Yui3在美团 2
Yui3在美团 2
 
Modular and Event-Driven JavaScript
Modular and Event-Driven JavaScriptModular and Event-Driven JavaScript
Modular and Event-Driven JavaScript
 
jQuery : Events are where it happens!
jQuery : Events are where it happens!jQuery : Events are where it happens!
jQuery : Events are where it happens!
 
G* on GAE/J 挑戦編
G* on GAE/J 挑戦編G* on GAE/J 挑戦編
G* on GAE/J 挑戦編
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
Building Robust jQuery Plugins
Building Robust jQuery PluginsBuilding Robust jQuery Plugins
Building Robust jQuery Plugins
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQuery
 

More from Morgan Cheng (6)

React & Redux in Hulu
React & Redux in HuluReact & Redux in Hulu
React & Redux in Hulu
 
Flux and redux
Flux and reduxFlux and redux
Flux and redux
 
Critical thinking in Node.js
Critical thinking in Node.jsCritical thinking in Node.js
Critical thinking in Node.js
 
High Performance Mobile Web
High Performance Mobile WebHigh Performance Mobile Web
High Performance Mobile Web
 
Single Page WebApp Architecture
Single Page WebApp ArchitectureSingle Page WebApp Architecture
Single Page WebApp Architecture
 
Secrets of Effective Presentation
Secrets of Effective PresentationSecrets of Effective Presentation
Secrets of Effective Presentation
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

Embracing YUI3 and Frontend Perf

  • 1. Embracing YUI 3 & Frontend Performance Morgan Cheng, Jan 6th 2011
  • 2. YUI 3 Lighter Faster Easier to use
  • 3. YUI 2 to YUI 3
  • 4. YUI 2 sample module YAHOO.namespace(‘MyProject’); (function() { var MODULE_NAME=“MyProject”, Dom = YAHOO.util.Dom; YAHOO.MyProject.MyDialog = function() { . . . }; }());
  • 5. Another YUI 2 sample module YAHOO.namespace(‘MyProject’); (function() { var MODULE_NAME=“MyProject”, Dom = YAHOO.util.Dom Event = YAHOO.util.Event; YAHOO.MyProject.MyPage = { init: function() { }, . . . }; Event.onDOMReady(YAHOO.MyProject.MyPage.init, null, YAHOO.MyProject.MyPage); }());
  • 6. Not Enough for Mash-up Page
  • 7. Limitation YAHOO property can be overwritten… YAHOO.widget.HelloWorld = something; // by one developer … YAHOO.widget.HelloWorld = another; // by another developer
  • 8. YUI 3 module YUI.add(“myModule”, function(Y) { Y.namespace(‘myproject’).mod = function() { }; }, “0.0.1”, //module version {requires: [‘node’]} // dependecies );
  • 9. Use YUI 3 module YUI().use(“myModule”, function(Y) { varm = new Y.myProject.mod; . . . }); This might be easy to read: varyui = YUI(); yui. use(“myModule”, function(Y) { varm = new Y.myProject.mod; . . . });
  • 10. Sandboxing YUI().use(“myModule”, function(Y) { varm = new Y.myProject.mod; }); YUI().use(“node”, function(Y) { //no myProject for this Y });
  • 11. DOM <div id=“menu”> <h1>B1 Canteen Menu</h1> <ul> <li>Fish</li> <li class=“promotion”>Noodle</li> <li class=“promotion”>Meat</li> <li>Rice</li> <li>Tomato</li> </ul> </div>
  • 12. In YUI 2 To get <li> element with “promotion” class under element with id “menu” var Dom = YAHOO.util.Dom; var el = Dom.get(‘menu’); varpromotedItems = Dom.getElementsByClassName(‘promotion’, ‘li’, el);
  • 13. Selector API in YUI 3 One-liner YUI().use(‘node’, function(Y) { varpromtedItems = Y.all(‘#menuli.promotion’); });
  • 14. Selector Best Practice Prefer “#id” Prefer simple selector over complex selector
  • 15. YUI 2 Selector Utility http://developer.yahoo.com/yui/selector/ But, not chainable returning raw Dom elements
  • 16. Node & NodeList Wrapper of DOM elements From function-based to object-based In YUI 2 var el = YAHOO.util.Dom.get(‘id’); YAHOO.util.Dom.addClass(el, ‘className’); In YUI 3 Y.one(‘id’).addClass(‘className’);
  • 17. YUI 3 Chainable YUI().use(‘node’, function(Y) { Y.all(“#menuli”) .each(function(node, i, ctx) { if ( i % 2) { node.addClass(‘even’).removeClass(‘disable’); } }) .setStyle(‘color, ‘red’); });
  • 18. Event Event Facade YUI().use(‘event’, ‘node’, function(Y) { Y.one(‘id’).on(‘click’, function(e) { Y.log(e.currentTarget); e.preventDefault(); }); });
  • 19. Wait, but how does these stuff get loaded into page?
  • 20. Seed File <script src="http://yui.yahooapis.com/3.2.0/build/yui/yui-min.js"></script> YUI().use(‘node’, function(Y) { });
  • 21. Seed File with Loader <script type="text/javascript" src="http://yui.yahooapis.com/combo?3.2.0/build/yui/yui-min.js&3.2.0/build/loader/loader-min.js"></script> YUI().use(‘node’, function(Y) { });
  • 22. Traditional Way <script type="text/javascript" src="http://yui.yahooapis.com/combo?3.2.0/build/yui/yui-min.js&3.2.0/build/loader/loader-min.js&3.2.0/build/oop/oop-min.js&3.2.0/build/dom/dom-min.js&3.2.0/build/dom/dom-style-ie-min.js&3.2.0/build/event-custom/event-custom-base-min.js&3.2.0/build/event/event-base-min.js&3.2.0/build/pluginhost/pluginhost-min.js&3.2.0/build/node/node-min.js&3.2.0/build/event/event-delegate-min.js"></script>
  • 23. YUI 3 Dependency Magic Ramp-up Combine
  • 25. Script Blocks Page Rendering <script type=“text/javascript” src=“long-time.js”></script> <imgsrc=“I-am-bocked.png”></img>
  • 26. Script Blocks Script <script type=“text/javascript” src=“long-time.js”></script> <script type=“text/javascript” src=“I-am-bocked.js”></script> post-IE8 browsers do asynchronous downloading
  • 27. Non-blocking JavaScript defer attribute async attribute iframe document.write XHR injection Commented Javascript JavaScript downloaded as Image & Object …
  • 28. Dynamic Script Tag function createScript(js) { var script = document.createElement(‘script’); script.type = ‘text/javascript’; script.async = “true”; var head = document.getElementsByTagname(‘head’)[0]; head.appendChild(script); }
  • 29. Execution Order Matters Execution order is not guaranteed to be preserved for asynchronous script loading YUI 3 is born to solve execution order problem each module payload is not executed until all dependencies are ready
  • 30. Don’t Get Excited Too Early
  • 31. Deficiency in YUI 3 Loader YUI().use blocks each other YUI().use(‘node’, function() { . . . }); YUI().use(‘event’, function() { . . . });
  • 32. Deficiency in YUI 3 Loader Disabling combo makes each module loaded in sequence YUI({ combine: false }).use(‘node’, ‘event’, function() { . . . });
  • 33. Prefetch YUI Loader hack http://bazaar.launchpad.net/~launchpad-pqm/lazr-js/toolchain/annotate/188/src-js/lazrjs/loader/prefetch.js
  • 34. Flickr Lesson #1 Firewall can cut your long URL http://yui.yahooapis.com/combo?3.2.0/build/yui/yui-min.js&3.2.0/build/oop/oop-min.js&3.2.0/build/event-custom/event-custom-min.js&3.2.0/build/event/event-base-min.js&3.2.0/build/pluginhost/pluginhost-min.js&3.2.0/build/attribute/attribute-min.js&3.2.0/build/dom/dom-min.js&3.2.0/build/dom/dom-style-ie-min.js&3.2.0/build/node/node-min.js&3.2.0/build/event/event-delegate-min.js&3.2.0/build/base/base-min.js&3.2.0/build/anim/anim-min.js&3.2.0/build/node/align-plugin-min.js&3.2.0/build/classnamemanager/classnamemanager-min.js&3.2.0/build/intl/intl-min.js&3.2.0/build/console/lang/console.js&3.2.0/build/event/event-synthetic-min.js&3.2.0/build/event/event-focus-min.js&3.2.0/build/widget/widget-min.js&3.2.0/build/dump/dump-min.js&3.2.0/build/substitute/substitute-min.js&3.2.0/build/console/console-min.js&3.2.0/build/plugin/plugin-min.js&3.2.0/build/console/console-filters-min.js&3.2.0/build/cookie/cookie-min.js&3.2.0/build/dom/dom-style-ie-min.js&3.2.0/build/event/event-resize-min.js&3.2.0/build/event/event-mouseenter-min.js&3.2.0/build/dd/dd-min.js&3.2.0/build/dd/dd-gestures-min.js&3.2.0/build/dd/dd-drop-plugin-min.js&3.2.0/build/dd/dd-plugin-min.js&3.2.0/build/event/event-touch-min.js&3.2.0/build/event-gestures/event-move-min.js&3.2.0/build/dd/dd-gestures-min.js&3.2.0/build/dataschema/dataschema-base-min.js&3.2.0/build/dataschema/dataschema-array-min.js&3.2.0/build/cache/cache-base-min.js&3.2.0/build/querystring/querystring-stringify-simple-min.js&3.2.0/build/io/io-base-min.js&3.2.0/build/json/json-min.js&3.2.0/build/dataschema/dataschema-json-min.js&3.2.0/build/dataschema/dataschema-text-min.js&3.2.0/build/dataschema/dataschema-xml-min.js&3.2.0/build/datasource/datasource-min.js
  • 35. Flickr Lesson #2 Sexy URL is not welcome http://… &xxw.js&xxx.js&…
  • 36. Multiple Pages Page A module A + B + C + D + E + X Page B module A + B + C + D + E + Y Page C module A + B + C + D + Z
  • 37. YUI 3 in Action
  • 39. Code Reuse Y.extend Y.augment Y.clone //deep copy by value Y.merge //mix-in multiple objects Y.aggregate
  • 40. Powerful Y.mix Y.mix(r, s, ov, wl, mode, merge) mode: 0. object to object 1. prototype to prototype 2. prototype to prototype and object props 3. prototype to object 4. object to prototype
  • 41. EventTarget publish fire on before after
  • 43. Base Initializer destrutor static property NAME as event prefix
  • 44. Widget render renderUI bindUI syncUI
  • 45. Plugin Y.namespace('QPlus').DigPlugin = Y.Base.create('Dig', Y.Plugin.Base, [], { //prototypal properties }, { // static properties });
  • 46. Plugin Prototypal Properties Initializer destuctor
  • 47. Plugin Static Properties NS Mandatory Used as host property name to reference plugin
  • 48. Use Plugin plug Trigger initializer unplug Trigger destructor
  • 49. AOP in YUI3 doBefore/onHostEvent/doAfter Y.SamplePlugin = Y.Base.create(‘sample’, Y.Plugin.Base, [], { initializer: function() { this.doBefore(‘someMethod’, function() { … } ); } }, { NS: ‘sample’ } );
  • 50. Custom Event Application Level De-coupling Identified by string
  • 51. YUI 2 Custom Event this.myEvent = new YAHOO.util.CustomEvent(‘myEvent’); this.myEvent.fire(); instance.myEvent.subscribe(doSomething);
  • 52. YUI 3 Custom Event Y.fire(‘chengguan-coming’, 1, 2, 3); Y.on(‘chengguan-coming’, function(arg1, arg2, arg3) { . . . });
  • 53. Advanced Custom Event this.publish(‘myEvent’, { broadcast: 2, //broadcast to all YUI instances defaultFn: handler // default event handler } ); this.fire(‘myEvent’); instance.on(‘myEvent’, doSomething);
  • 54. Consistent Event API instance.on(‘click’, onClick); instance.on(‘myEvent’, doSomething);
  • 55. Synthetic Event Extend DOM event Y.Event.define(‘flick’, { on: function(node, subscription, notifier) { }, detach: function(node, subscription notifier) { } });
  • 57. No iframe iframe is slow iframerequires one more HTTP roundtrip iframe makes your application complicated
  • 58. Flush Early Flush early and user view result early Flush early and external resources starts downloading early
  • 59. MVC might hurt your performance Model View Controller
  • 60. How ySymfony MVC works <head> </head> <body> <div id=“hd”></div> <div id=“bd”> <?php echo $sf_content?> </div> <div id=“ft”></div> </body> Lib Action Template
  • 61. Enable Early Flush in ySymfony Don’t use layout setLayout(false) Fetch partial and flush it in Action getPartial flush Customize web response class to avoid head() after flush()
  • 62. Don’t <html> . . . <body> <div> <div id=‘hd’></div> <?php flush(); ?> <? // some browser would not render till getting closing tag ?> <div id=‘bd’></div> <?php flush(); ?> <div id=‘ft’></div> </div> </body> </html>
  • 63. Do <html> . . . <body> <div id=‘hd’></div> <?php flush(); ?> <div id=‘bd’></div> <?php flush(); ?> <div id=‘ft’></div> </body> </html>
  • 65. JavaScript Loading Strategy Dynamic Script Tag Concatenate JavaScript into single file with FUSE
  • 66. Users are Not Patient User might start interact with the page before its JavaScript module is loaded It is not good to not respond to user interaction
  • 67. Put User Actions into Queue
  • 68. Event-Binder: A Tale of Two JavaScripts Inline Script Prevent default behavior Show progressive UI Put event into queue External Script Flush events from queue Hide progressive UI Remove former event handler
  • 70. YUI 3 Resources http://developer.yahoo.com/yui/3/ http://yuiblog.com/ http://twitter.com/miraglia/yui/members yui-users@yahoo-inc.com
  • 71. Web Performance Resources http://stevesouders.com/ http://www.perfplanet.com/ Velocity