SlideShare a Scribd company logo
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!

More Related Content

What's hot

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
Mark Baker
 
XML-Motor
XML-MotorXML-Motor
XML-Motor
Abhishek Kumar
 
Gearman jobqueue
Gearman jobqueueGearman jobqueue
Gearman jobqueue
Magento 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 Python
Luca Mearelli
 
A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your App
Luca Mearelli
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
Domenic Denicola
 
Into the ZF2 Service Manager
Into the ZF2 Service ManagerInto the ZF2 Service Manager
Into the ZF2 Service Manager
Chris Tankersley
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To Batch
Luca Mearelli
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
Matt 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 2015
Fernando 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
 
Map kit light
Map kit lightMap kit light
Map kit light
CocoaHeads France
 
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
Konstantin Kudryashov
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
BoneyGawande
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
Frank de Jonge
 
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
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
Bo-Young Park
 
Swift Sequences & Collections
Swift Sequences & CollectionsSwift Sequences & Collections
Swift Sequences & Collections
CocoaHeads France
 
RxSwift to Combine
RxSwift to CombineRxSwift to Combine
RxSwift to Combine
Bo-Young Park
 

What's hot (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
 

Viewers also liked

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/Technology
Debojyoti Dutta
 
Jan 2012 HUG: Storm
Jan 2012 HUG: StormJan 2012 HUG: Storm
Jan 2012 HUG: Storm
Yahoo Developer Network
 
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
DataWorks Summit
 
Developing a National Telemedicine Network
Developing a National Telemedicine NetworkDeveloping a National Telemedicine Network
Developing a National Telemedicine Network
Health Informatics New Zealand
 
RDO hangout on gnocchi
RDO hangout on gnocchiRDO hangout on gnocchi
RDO hangout on gnocchi
Eoghan 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 acg
Jeffrey 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 Repair
Cloudera, Inc.
 
Heka - Rob Miller
Heka - Rob MillerHeka - Rob Miller
Heka - Rob Miller
Devopsdays
 
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
Stefano 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 JVM
David Wu
 
Hive integration: HBase and Rcfile__HadoopSummit2010
Hive integration: HBase and Rcfile__HadoopSummit2010Hive integration: HBase and Rcfile__HadoopSummit2010
Hive integration: HBase and Rcfile__HadoopSummit2010
Yahoo Developer Network
 
The innerHTML Apocalypse
The innerHTML ApocalypseThe innerHTML Apocalypse
The innerHTML Apocalypse
Mario Heiderich
 
Attribution and ROI Measurement
Attribution and ROI MeasurementAttribution and ROI Measurement
Attribution and ROI Measurement
Encore Media Metrics
 
Openshift + Openstack + Fedora = Awesome
Openshift + Openstack + Fedora = AwesomeOpenshift + Openstack + Fedora = Awesome
Openshift + Openstack + Fedora = Awesome
Mark Atwood
 
Mobile input lukew
Mobile input lukewMobile input lukew
Mobile input lukew
Youssef Rahoui
 
Programmer Anarchy (English)
Programmer Anarchy (English)Programmer Anarchy (English)
Programmer Anarchy (English)
Fred George
 

Viewers also liked (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)
 

Similar to 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 JavaScript
Ryan Anklam
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Colin DeCarlo
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 
Android workshop
Android workshopAndroid workshop
Android workshop
Michael Galpin
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
Ara 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 you
Simon 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 Practices
Siarhei Barysiuk
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
My java file
My java fileMy java file
My java file
Anamika Chauhan
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
celenarouzie
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
Eduard Tomàs
 
Building Smart Async Functions For Mobile
Building Smart Async Functions For MobileBuilding Smart Async Functions For Mobile
Building Smart Async Functions For Mobile
Glan Thomas
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
dion
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming En
guest9bcef2f
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)
Davide Cerbo
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
Taha 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 journey
Huiyi Yan
 

Similar to 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 En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming En
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)
 
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
 

More from Morgan Cheng

React & Redux in Hulu
React & Redux in HuluReact & Redux in Hulu
React & Redux in Hulu
Morgan Cheng
 
Flux and redux
Flux and reduxFlux and redux
Flux and redux
Morgan Cheng
 
Critical thinking in Node.js
Critical thinking in Node.jsCritical thinking in Node.js
Critical thinking in Node.js
Morgan 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 Web
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
 
Single Page WebApp Architecture
Single Page WebApp ArchitectureSingle Page WebApp Architecture
Single Page WebApp Architecture
Morgan Cheng
 
Secrets of Effective Presentation
Secrets of Effective PresentationSecrets of Effective Presentation
Secrets of Effective Presentation
Morgan Cheng
 
Optimize URL for Performance
Optimize URL for PerformanceOptimize URL for Performance
Optimize URL for Performance
Morgan Cheng
 
F2E's Creeds
F2E's CreedsF2E's Creeds
F2E's Creeds
Morgan Cheng
 
Comet Server Push Over Web
Comet Server Push Over WebComet Server Push Over Web
Comet Server Push Over Web
Morgan 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 YUI
Morgan Cheng
 
Embracing YUI3 and Frontend Perf
Embracing YUI3 and Frontend PerfEmbracing YUI3 and Frontend Perf
Embracing YUI3 and Frontend Perf
Morgan Cheng
 

More from 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
 

Recently uploaded

zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
HarisZaheer8
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
Data Hops
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 

Recently uploaded (20)

zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
AWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptxAWS Cloud Cost Optimization Presentation.pptx
AWS Cloud Cost Optimization Presentation.pptx
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 

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