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

More Related Content

What's hot

Gearman jobqueue
Gearman jobqueueGearman jobqueue
Gearman jobqueue
Magento Dev
 
Controlling The Cloud With Python
Controlling The Cloud With PythonControlling The Cloud With Python
Controlling The Cloud With Python
Luca Mearelli
 

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 Certificate
Abdulkader Alshereef
 
2012 php conf slide PIXNET 如何使用 php
2012 php conf slide   PIXNET 如何使用 php2012 php conf slide   PIXNET 如何使用 php
2012 php conf slide PIXNET 如何使用 php
ronnywang_tw
 
Heka - Rob Miller
Heka - Rob MillerHeka - Rob Miller
Heka - Rob Miller
Devopsdays
 
Openshift + Openstack + Fedora = Awesome
Openshift + Openstack + Fedora = AwesomeOpenshift + Openstack + Fedora = Awesome
Openshift + Openstack + Fedora = Awesome
Mark Atwood
 
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

The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
celenarouzie
 
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
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
Taha Shakeel
 

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 (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
 

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

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

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