SlideShare uma empresa Scribd logo
1 de 74
Build Lightweight Web Module Morgan Cheng @morgancheng May 26th, 2011
Expand Thriving Web Site
Inject Your Content Into Other Sites
Partner Website Server Your Website Server Browser
Partner Website Server Your Website Server Web Module Browser
Cross Domain
JSONP
Inject Content with JSONP Create one hidden element Send JSONP request  When JSONP data is received, compose HTML Fill the hidden element with composed HTML Show hidden element
Inject an iframe
iframe covering whole viewport
It is easy to create abigiframe. The hard part is how to close it.
Same Domain Callback Hidden Proxy Iframe
Time to Wear Hacker’s Hat
Cannot be “javascript: … ” Hidden Proxy Iframe
API Design First
<script src=“XXXXX_loader.js”></script><script>XXXXX.load(parameter);</script>
YAHOO.ABC.load(parameter);
YAHOO.ABC.load(parameter); Y.ABC.load(parameter);
YAHOO.ABC.load(parameter); Y.ABC.load(parameter); YABC.load(parameter);
YABC.load( 	‘wretch’, // appid. Mandatory 	1234, 		// spaceid. Mandatory 	100 	// delay in ms. Optional );
YABC.load( 	‘wretch’, // appid. Mandatory 	1234, 		// spaceid. Mandatory 	100, 	// delay in ms. Optional    	‘tw’		// intl. Mandatory ); What if new Mandatory parameter is added?
YABC.load({ appid: ‘wretch’, spaceid: ‘1234’,     delay: 100, intl: ‘tw’ }); Better! Config Object Pattern
Be Disciplined
Rules #1:  Don’t Assume Too Much on Hosting Page What? You Don’t Have YUI?
Rules #2:  Don’t Be Obstructive to Hosting Page
Rules #3:  Don’t Impact Hosting Page Performance
In a Word, We Have To DIY
And, It MUST Be Lightweight
Simplest Feature vs. Rich Feature
YAHOO.util.Connect.asyncRequest( 	‘GET’, 	‘http://www.example.com/jsonp’, 	{ success: sucessHandler, failure: failureHandler, argument: argumentObj 	}, postData };
We Don’t Need Full Feature YAHOO.util.Connect.asyncRequest( 	‘GET’, 	‘http://www.example.com/jsonp’, 	{ success: sucessHandler, failure: failureHandler, argument: argumentObj 	}, postData };
This is What We Need
Minify-Friendly JavaScript
/*   * Gets query string presentation of given object.   */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key]));     }     return encParams.join('&'); }
/*   * Gets query string presentation of given object.   */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key]));     }     return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Before 287 bytes After 119 bytes Compression Rate: 59% Minify
What Can Be Minified?
/*   * Gets query string presentation of given object.   */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key]));     }     return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Comments are stripped
/*   * Gets query string presentation of given object.   */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key]));     }     return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Unnecessary White Spaces are Stripped
/*   * Gets query string presentation of given object.   */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key]));     }     return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Argument Names are Obfuscated
/*   * Gets query string presentation of given object.   */ function toQueryString(params) { varencParams= [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key]));     }     return encParams.join('&'); } function toQueryString(c){vara=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Local Variable Names are Minified
What Can NOT Be Minified?
/*   * Gets query string presentation of given object.   */ functiontoQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key]));     } return encParams.join('&'); } functiontoQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Keywords are NOT Minified
/*   * Gets query string presentation of given object.   */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key]));     }     return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Global Variables are NOT Minified
/*   * Gets query string presentation of given object.   */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key]));     }     return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Object Properties are NOT Minified
/*   * Gets query string presentation of given object.   */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key]));     }     return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; How About This?
Wait, Do We Need Minify If All Browsers Support Gzip?
JavaScript? Gzip Gzip is no-loss compressionIt Doesn’t Understand JavaScript
~15% “Accept-Encoding: gzip, deflate”HTTP Headers Are Stripped
Evolution of Code
YABC = { load: function() { 			// do something     } };
YABC = { privateVariable: ‘hello’, privateFunction: function() {            // do some private thing     }, load: function() { 			// do something     } };
YABC = { privateVariable: ‘hello’, privateFunction: function() {            // do some helping     }, load: function() { 			// do something     } }; Not Minifiable
(function() { var _privateVariable = ‘hello’; function _privateFunction () { 	// do some private thing } YABC = {     load: function() { 			// do something     } }; }()) Immediate Function Pattern
(function() { var_privateVariable= ‘hello’; function _privateFunction() { 	// do some private thing } YABC = {     load: function() { 			// do something     } }; }()) Minifiable
(function() { var win = window;  _privateVariable = ‘hello’; function _privateFunction () { 	// do some private thing } YABC = {     load: function() { 			// do something     } }; }()) “window” is used more than once
(function() { var win = window;  _privateVariable = ‘hello’; function _privateFunction () { 	// do some private thing } YABC = {     unload: function() {     },     load: function() { 			// do something     } }; }())
(function() { var win = window;  _privateVariable = ‘hello’; function _privateFunction () { 	// do some private thing } YABC = { unload: function() {     },     load: function() { 			// do something     } }; }()) Every invocation of this method has to be “YABC.unload”
(function() { var win = window;  _privateVariable = ‘hello’, yabc; function _privateFunction () { 	// do some private thing } varyabc= { unload: function() {     },     load: function() { 			// do something     } }; YABC = yabc; }()) Local Invocation of “yabc.unload” can be minfied
(function() { var win = window;  _privateVariable = ‘hello’, yabc; function _privateFunction () { 	// do some private thing } varyabc= {     unload: function() {     },     load: function() { 			// do something     } }; YABC = yabc; }()) YUI Developers, Looks Familiar?
Be a JavaScript Ninjia
(function() { 	// immediate functioning }())
(function() { 	// immediate functioning }()) !function() { 	// immediate functioning }() Saving 1 Byte
if (-1===indexOf(foo,’bar’)) { 	// do something }
if (-1!==foo.indexOf(’bar’)) { 	// do something } if (~foo.indexOf(’bar’)) { 	// do something } Saving 4 Bytes
function escapeHTML(s) { 	return s.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g,'&lt;').replace(/"/g, '&quot').replace(/'/g,'&#x27;').replace(//g,'&#x2F;'); }
function escapeHTML(s) { 	return s.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g,'&lt;').replace(/"/g, '&quot').replace(/'/g,'&#x27;').replace(//g,'&#x2F;'); } function escapeHTML(s, r) { r='replace';returns[r](/&/g,'&amp;')[r](/>/g,'&gt;')[r](/</g,'&lt;')[r](/"/g, '&quot')[r](/'/g,'&#x27;')[r](//g,'&#x2F;’); } Saving 19 Bytes
History of code size
JavaScript is NOT SlowBut, DOM is Slow
Module Versioning
Traditionally … http://www.example.com/v1/loader.js http://www.example.com/loader_20110510.js
Short Time Caching
Takeaways Make your partners happy Hack your own code. Hack it Hard! Minify JavaScript Code
Thank You!

Mais conteúdo relacionado

Mais procurados

A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsMark Baker
 
Gearman jobqueue
Gearman jobqueueGearman jobqueue
Gearman jobqueueMagento Dev
 
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...Ville Mattila
 
Controlling The Cloud With Python
Controlling The Cloud With PythonControlling The Cloud With Python
Controlling The Cloud With PythonLuca Mearelli
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your AppLuca Mearelli
 
Into the ZF2 Service Manager
Into the ZF2 Service ManagerInto the ZF2 Service Manager
Into the ZF2 Service ManagerChris Tankersley
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To BatchLuca Mearelli
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For BeginnersMatt Passell
 
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015Fernando Hamasaki de Amorim
 
And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...Codemotion
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Konstantin Kudryashov
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Dhaval Dalal
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & CollectionsCocoaHeads France
 

Mais procurados (20)

A Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP GeneratorsA Functional Guide to Cat Herding with PHP Generators
A Functional Guide to Cat Herding with PHP Generators
 
XML-Motor
XML-MotorXML-Motor
XML-Motor
 
Gearman jobqueue
Gearman jobqueueGearman jobqueue
Gearman jobqueue
 
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...
 
Controlling The Cloud With Python
Controlling The Cloud With PythonControlling The Cloud With Python
Controlling The Cloud With Python
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your App
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Into the ZF2 Service Manager
Into the ZF2 Service ManagerInto the ZF2 Service Manager
Into the ZF2 Service Manager
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To Batch
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
 
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
 
And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...
 
Map kit light
Map kit lightMap kit light
Map kit light
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
 

Destaque

ASME Course Attendance Certificate
ASME Course Attendance CertificateASME Course Attendance Certificate
ASME Course Attendance CertificateAbdulkader Alshereef
 
2012 php conf slide PIXNET 如何使用 php
2012 php conf slide   PIXNET 如何使用 php2012 php conf slide   PIXNET 如何使用 php
2012 php conf slide PIXNET 如何使用 phpronnywang_tw
 
Donabe - Basic Models/Technology
Donabe - Basic Models/TechnologyDonabe - Basic Models/Technology
Donabe - Basic Models/TechnologyDebojyoti Dutta
 
Pig on Tez: Low Latency Data Processing with Big Data
Pig on Tez: Low Latency Data Processing with Big DataPig on Tez: Low Latency Data Processing with Big Data
Pig on Tez: Low Latency Data Processing with Big DataDataWorks Summit
 
RDO hangout on gnocchi
RDO hangout on gnocchiRDO hangout on gnocchi
RDO hangout on gnocchiEoghan Glynn
 
Golden age for technology and innovation vfinal acg
Golden age for technology and innovation vfinal acgGolden age for technology and innovation vfinal acg
Golden age for technology and innovation vfinal acgJeffrey Bussgang
 
Hadoop Integration with Microstrategy
Hadoop Integration with Microstrategy Hadoop Integration with Microstrategy
Hadoop Integration with Microstrategy snehal parikh
 
Hadoop Summit 2012 | Improving HBase Availability and Repair
Hadoop Summit 2012 | Improving HBase Availability and RepairHadoop Summit 2012 | Improving HBase Availability and Repair
Hadoop Summit 2012 | Improving HBase Availability and RepairCloudera, Inc.
 
Heka - Rob Miller
Heka - Rob MillerHeka - Rob Miller
Heka - Rob MillerDevopsdays
 
Http Parameter Pollution, a new category of web attacks
Http Parameter Pollution, a new category of web attacksHttp Parameter Pollution, a new category of web attacks
Http Parameter Pollution, a new category of web attacksStefano Di Paola
 
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)Nicholas Zakas
 
Development with Vert.x: an event-driven application framework for the JVM
Development with Vert.x: an event-driven application framework for the JVMDevelopment with Vert.x: an event-driven application framework for the JVM
Development with Vert.x: an event-driven application framework for the JVMDavid Wu
 
Hive integration: HBase and Rcfile__HadoopSummit2010
Hive integration: HBase and Rcfile__HadoopSummit2010Hive integration: HBase and Rcfile__HadoopSummit2010
Hive integration: HBase and Rcfile__HadoopSummit2010Yahoo Developer Network
 
The innerHTML Apocalypse
The innerHTML ApocalypseThe innerHTML Apocalypse
The innerHTML ApocalypseMario Heiderich
 
Openshift + Openstack + Fedora = Awesome
Openshift + Openstack + Fedora = AwesomeOpenshift + Openstack + Fedora = Awesome
Openshift + Openstack + Fedora = AwesomeMark Atwood
 
Programmer Anarchy (English)
Programmer Anarchy (English)Programmer Anarchy (English)
Programmer Anarchy (English)Fred George
 

Destaque (20)

ASME Course Attendance Certificate
ASME Course Attendance CertificateASME Course Attendance Certificate
ASME Course Attendance Certificate
 
2012 php conf slide PIXNET 如何使用 php
2012 php conf slide   PIXNET 如何使用 php2012 php conf slide   PIXNET 如何使用 php
2012 php conf slide PIXNET 如何使用 php
 
Donabe - Basic Models/Technology
Donabe - Basic Models/TechnologyDonabe - Basic Models/Technology
Donabe - Basic Models/Technology
 
Jan 2012 HUG: Storm
Jan 2012 HUG: StormJan 2012 HUG: Storm
Jan 2012 HUG: Storm
 
Pig on Tez: Low Latency Data Processing with Big Data
Pig on Tez: Low Latency Data Processing with Big DataPig on Tez: Low Latency Data Processing with Big Data
Pig on Tez: Low Latency Data Processing with Big Data
 
Developing a National Telemedicine Network
Developing a National Telemedicine NetworkDeveloping a National Telemedicine Network
Developing a National Telemedicine Network
 
RDO hangout on gnocchi
RDO hangout on gnocchiRDO hangout on gnocchi
RDO hangout on gnocchi
 
Golden age for technology and innovation vfinal acg
Golden age for technology and innovation vfinal acgGolden age for technology and innovation vfinal acg
Golden age for technology and innovation vfinal acg
 
Hadoop Integration with Microstrategy
Hadoop Integration with Microstrategy Hadoop Integration with Microstrategy
Hadoop Integration with Microstrategy
 
Hadoop Summit 2012 | Improving HBase Availability and Repair
Hadoop Summit 2012 | Improving HBase Availability and RepairHadoop Summit 2012 | Improving HBase Availability and Repair
Hadoop Summit 2012 | Improving HBase Availability and Repair
 
Heka - Rob Miller
Heka - Rob MillerHeka - Rob Miller
Heka - Rob Miller
 
Http Parameter Pollution, a new category of web attacks
Http Parameter Pollution, a new category of web attacksHttp Parameter Pollution, a new category of web attacks
Http Parameter Pollution, a new category of web attacks
 
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)
 
Development with Vert.x: an event-driven application framework for the JVM
Development with Vert.x: an event-driven application framework for the JVMDevelopment with Vert.x: an event-driven application framework for the JVM
Development with Vert.x: an event-driven application framework for the JVM
 
Hive integration: HBase and Rcfile__HadoopSummit2010
Hive integration: HBase and Rcfile__HadoopSummit2010Hive integration: HBase and Rcfile__HadoopSummit2010
Hive integration: HBase and Rcfile__HadoopSummit2010
 
The innerHTML Apocalypse
The innerHTML ApocalypseThe innerHTML Apocalypse
The innerHTML Apocalypse
 
Attribution and ROI Measurement
Attribution and ROI MeasurementAttribution and ROI Measurement
Attribution and ROI Measurement
 
Openshift + Openstack + Fedora = Awesome
Openshift + Openstack + Fedora = AwesomeOpenshift + Openstack + Fedora = Awesome
Openshift + Openstack + Fedora = Awesome
 
Mobile input lukew
Mobile input lukewMobile input lukew
Mobile input lukew
 
Programmer Anarchy (English)
Programmer Anarchy (English)Programmer Anarchy (English)
Programmer Anarchy (English)
 

Semelhante a Build Lightweight Web Module

Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for youSimon Willison
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPresswpnepal
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxcelenarouzie
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For MobileGlan Thomas
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Davide Cerbo
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming Enguest9bcef2f
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access RunbookTaha Shakeel
 
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 journeyHuiyi Yan
 

Semelhante a Build Lightweight Web Module (20)

Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
My java file
My java fileMy java file
My java file
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For Mobile
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming En
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
 
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
 

Mais de Morgan Cheng

React & Redux in Hulu
React & Redux in HuluReact & Redux in Hulu
React & Redux in HuluMorgan Cheng
 
Critical thinking in Node.js
Critical thinking in Node.jsCritical thinking in Node.js
Critical thinking in Node.jsMorgan Cheng
 
Engineering excellence 卓越工程
Engineering excellence 卓越工程Engineering excellence 卓越工程
Engineering excellence 卓越工程Morgan Cheng
 
High Performance Mobile Web
High Performance Mobile WebHigh Performance Mobile Web
High Performance Mobile WebMorgan 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 AppMorgan Cheng
 
Single Page WebApp Architecture
Single Page WebApp ArchitectureSingle Page WebApp Architecture
Single Page WebApp ArchitectureMorgan Cheng
 
Secrets of Effective Presentation
Secrets of Effective PresentationSecrets of Effective Presentation
Secrets of Effective PresentationMorgan Cheng
 
Optimize URL for Performance
Optimize URL for PerformanceOptimize URL for Performance
Optimize URL for PerformanceMorgan Cheng
 
Comet Server Push Over Web
Comet Server Push Over WebComet Server Push Over Web
Comet Server Push Over WebMorgan Cheng
 
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 YUIMorgan Cheng
 
Embracing YUI3 and Frontend Perf
Embracing YUI3 and Frontend PerfEmbracing YUI3 and Frontend Perf
Embracing YUI3 and Frontend PerfMorgan Cheng
 

Mais de Morgan Cheng (13)

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
 
Engineering excellence 卓越工程
Engineering excellence 卓越工程Engineering excellence 卓越工程
Engineering excellence 卓越工程
 
High Performance Mobile Web
High Performance Mobile WebHigh Performance Mobile Web
High Performance Mobile Web
 
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
 
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
 
Optimize URL for Performance
Optimize URL for PerformanceOptimize URL for Performance
Optimize URL for Performance
 
F2E's Creeds
F2E's CreedsF2E's Creeds
F2E's Creeds
 
Comet Server Push Over Web
Comet Server Push Over WebComet Server Push Over Web
Comet Server Push Over Web
 
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
 
Embracing YUI3 and Frontend Perf
Embracing YUI3 and Frontend PerfEmbracing YUI3 and Frontend Perf
Embracing YUI3 and Frontend Perf
 

Último

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Último (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Build Lightweight Web Module

  • 1. Build Lightweight Web Module Morgan Cheng @morgancheng May 26th, 2011
  • 3. Inject Your Content Into Other Sites
  • 4. Partner Website Server Your Website Server Browser
  • 5. Partner Website Server Your Website Server Web Module Browser
  • 8. Inject Content with JSONP Create one hidden element Send JSONP request When JSONP data is received, compose HTML Fill the hidden element with composed HTML Show hidden element
  • 10.
  • 12. It is easy to create abigiframe. The hard part is how to close it.
  • 13. Same Domain Callback Hidden Proxy Iframe
  • 14. Time to Wear Hacker’s Hat
  • 15. Cannot be “javascript: … ” Hidden Proxy Iframe
  • 21. YABC.load( ‘wretch’, // appid. Mandatory 1234, // spaceid. Mandatory 100 // delay in ms. Optional );
  • 22. YABC.load( ‘wretch’, // appid. Mandatory 1234, // spaceid. Mandatory 100, // delay in ms. Optional ‘tw’ // intl. Mandatory ); What if new Mandatory parameter is added?
  • 23. YABC.load({ appid: ‘wretch’, spaceid: ‘1234’, delay: 100, intl: ‘tw’ }); Better! Config Object Pattern
  • 25. Rules #1: Don’t Assume Too Much on Hosting Page What? You Don’t Have YUI?
  • 26. Rules #2: Don’t Be Obstructive to Hosting Page
  • 27. Rules #3: Don’t Impact Hosting Page Performance
  • 28. In a Word, We Have To DIY
  • 29. And, It MUST Be Lightweight
  • 30. Simplest Feature vs. Rich Feature
  • 31. YAHOO.util.Connect.asyncRequest( ‘GET’, ‘http://www.example.com/jsonp’, { success: sucessHandler, failure: failureHandler, argument: argumentObj }, postData };
  • 32. We Don’t Need Full Feature YAHOO.util.Connect.asyncRequest( ‘GET’, ‘http://www.example.com/jsonp’, { success: sucessHandler, failure: failureHandler, argument: argumentObj }, postData };
  • 33. This is What We Need
  • 35. /* * Gets query string presentation of given object. */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key])); } return encParams.join('&'); }
  • 36. /* * Gets query string presentation of given object. */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key])); } return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Before 287 bytes After 119 bytes Compression Rate: 59% Minify
  • 37. What Can Be Minified?
  • 38. /* * Gets query string presentation of given object. */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key])); } return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Comments are stripped
  • 39. /* * Gets query string presentation of given object. */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key])); } return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Unnecessary White Spaces are Stripped
  • 40. /* * Gets query string presentation of given object. */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key])); } return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Argument Names are Obfuscated
  • 41. /* * Gets query string presentation of given object. */ function toQueryString(params) { varencParams= [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key])); } return encParams.join('&'); } function toQueryString(c){vara=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Local Variable Names are Minified
  • 42. What Can NOT Be Minified?
  • 43. /* * Gets query string presentation of given object. */ functiontoQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key])); } return encParams.join('&'); } functiontoQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Keywords are NOT Minified
  • 44. /* * Gets query string presentation of given object. */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key])); } return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Global Variables are NOT Minified
  • 45. /* * Gets query string presentation of given object. */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key])); } return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; Object Properties are NOT Minified
  • 46. /* * Gets query string presentation of given object. */ function toQueryString(params) { varencParams = [], encode = encodeURIComponent; for(key in params) { encParams.push(encode(key) + '=' + encode(params[key])); } return encParams.join('&'); } function toQueryString(c){var a=[],b=encodeURIComponent;for(key in c){a.push(b(key)+"="+b(c[key]))}returna.join("&")}; How About This?
  • 47. Wait, Do We Need Minify If All Browsers Support Gzip?
  • 48. JavaScript? Gzip Gzip is no-loss compressionIt Doesn’t Understand JavaScript
  • 49. ~15% “Accept-Encoding: gzip, deflate”HTTP Headers Are Stripped
  • 51. YABC = { load: function() { // do something } };
  • 52. YABC = { privateVariable: ‘hello’, privateFunction: function() { // do some private thing }, load: function() { // do something } };
  • 53. YABC = { privateVariable: ‘hello’, privateFunction: function() { // do some helping }, load: function() { // do something } }; Not Minifiable
  • 54. (function() { var _privateVariable = ‘hello’; function _privateFunction () { // do some private thing } YABC = { load: function() { // do something } }; }()) Immediate Function Pattern
  • 55. (function() { var_privateVariable= ‘hello’; function _privateFunction() { // do some private thing } YABC = { load: function() { // do something } }; }()) Minifiable
  • 56. (function() { var win = window; _privateVariable = ‘hello’; function _privateFunction () { // do some private thing } YABC = { load: function() { // do something } }; }()) “window” is used more than once
  • 57. (function() { var win = window; _privateVariable = ‘hello’; function _privateFunction () { // do some private thing } YABC = { unload: function() { }, load: function() { // do something } }; }())
  • 58. (function() { var win = window; _privateVariable = ‘hello’; function _privateFunction () { // do some private thing } YABC = { unload: function() { }, load: function() { // do something } }; }()) Every invocation of this method has to be “YABC.unload”
  • 59. (function() { var win = window; _privateVariable = ‘hello’, yabc; function _privateFunction () { // do some private thing } varyabc= { unload: function() { }, load: function() { // do something } }; YABC = yabc; }()) Local Invocation of “yabc.unload” can be minfied
  • 60. (function() { var win = window; _privateVariable = ‘hello’, yabc; function _privateFunction () { // do some private thing } varyabc= { unload: function() { }, load: function() { // do something } }; YABC = yabc; }()) YUI Developers, Looks Familiar?
  • 61. Be a JavaScript Ninjia
  • 62. (function() { // immediate functioning }())
  • 63. (function() { // immediate functioning }()) !function() { // immediate functioning }() Saving 1 Byte
  • 65. if (-1!==foo.indexOf(’bar’)) { // do something } if (~foo.indexOf(’bar’)) { // do something } Saving 4 Bytes
  • 66. function escapeHTML(s) { return s.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g,'&lt;').replace(/"/g, '&quot').replace(/'/g,'&#x27;').replace(//g,'&#x2F;'); }
  • 67. function escapeHTML(s) { return s.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g,'&lt;').replace(/"/g, '&quot').replace(/'/g,'&#x27;').replace(//g,'&#x2F;'); } function escapeHTML(s, r) { r='replace';returns[r](/&/g,'&amp;')[r](/>/g,'&gt;')[r](/</g,'&lt;')[r](/"/g, '&quot')[r](/'/g,'&#x27;')[r](//g,'&#x2F;’); } Saving 19 Bytes
  • 69. JavaScript is NOT SlowBut, DOM is Slow
  • 71. Traditionally … http://www.example.com/v1/loader.js http://www.example.com/loader_20110510.js
  • 73. Takeaways Make your partners happy Hack your own code. Hack it Hard! Minify JavaScript Code