SlideShare uma empresa Scribd logo
1 de 49
JavaScript
Performance



                        stevesouders.com/docs/sfjs-20120112.pptx
      Disclaimer: This content does not necessarily reflect the opinions of my employer.
YSlow   Cuzillion SpriteMe Hammerhead
Web
WPO       Performance
          Optimization
drives traffic
improves UX
increases revenue
reduces costs
What’s the #1
cause of slow
web pages?
JAVASCRIPT!
all requests containing “.js” are skipped
http://httparchive.org/trends.php?s=intersection
1995: scripts in HEAD
  <head>
  <script src=‘a.js’></script>
  </head>
blocks other downloads (IE 6-7, images
  in IE, iframes)
downloaded sequentially (IE 6-7)
blocks rendering during download &
  parse-execute
2007: move scripts to bottom
   ...
   <script src=‘a.js’></script>
   </body>
 doesn’t block other downloads
 downloaded sequentially in IE 6-7
 blocks rendering during download &
   parse-execute
2009: load scripts async
  var se =
   document.createElement(‘script’)
   ;
  se.src = ‘a.js’;
  document.getElementsByTagName(‘he
   ad’)[0].appendChild(se);

doesn’t block other downloads
downloaded in parallel (all browsers)
blocks rendering during parse-execute
2010: async + on-demand exec
   var se = new Image(); // Object
   se.onload = registerScript;
   se.src = ‘a.js’;

 separate download from parse-execute
 doesn’t block other downloads
 downloaded in parallel (all browsers)
 doesn’t block rendering until demanded
20??: markup
script async & defer
parsing doesn’t wait for script:
  • async – executed when available
  • defer – executed when parsing finished
when is it downloaded?




missing:
  • defer download AND execution
  • async/defer download, execute on demand
20??: markup
  <script src=‘a.js’
   [async|defer|noexecute]
   [deferdownload]>
doesn’t block downloads
downloaded in parallel
doesn’t block rendering until demanded
doesn’t contend for a connection
easier
ControlJS
  a JavaScript module for making scripts load faster

just change HTML
inline & external scripts
  <script type=‘text/cjs’
          data-cjssrc=‘main.js’>
  </script>

  <script type=‘text/cjs’>
  var name = getName();
  </script>
 http://controljs.org/
ControlJS
  a JavaScript module for making scripts load faster

download without executing
  <script type=‘text/cjs’
          data-cjssrc=‘main.js’
          data-cjsexec=false>
  <script>


Later if/when needed:
  CJS.execScript(src);
GMail Mobile
<script type=‘text/javascript’>
/*
var ...
*/
</script>

get script DOM element's text
remove comments
eval() when invoked
awesome for prefetching JS that might
  (not) be needed
http://goo.gl/l5ZLQ
localStorage
yuiblog.com/blog/2007/01/04/performance-research-part-2/
blaze.io/mobile/understanding-mobile-cache-sizes/
Home screen apps on iPhone are slower
because resources are re-requested
even though they should be read from
cache.
localStorage
window.localStorage:
   setItem()
   getItem()
   removeItem()
   clear()
also sessionStorage
all popular browsers, 5MB max
http://dev.w3.org/html5/webstorage/
http://diveintohtml5.org/storage.html
localStorage as cache
1st doc: write JS & CSS blocks to localStorage
   mres.-0yDUQJ03U8Hjija: <script>(function(){...

set cookie with entries & version
   MRES=-0yDUQJ03U8Hjija:-4EaJoFuDoX0iloI:...

later docs: read JS & CSS from localStorage
   document.write( localStorage.getItem(mres.-
     0yDUQJ03U8Hjija) );


http://stevesouders.com/blog/2011/03/28/storager-case-
  study-bing-google/
Google Analytics Async Snippet

var ga = document.createElement(‘script’);
ga.type = ‘text/javascript’;
ga.async = true;
ga.src = (‘https:’ ==
  document.location.protocol ? ‘https://ssl’ :
  ‘http://www’)+‘.google-analytics.com/ga.js’;
var s =
  document.getElementsByTagName(‘script’)[
  0];
s.parentNode.insertBefore(ga, s);

code.google.com/apis/analytics/docs/tracking/asyncTracking.html
var ga = document.createElement(‘script’);
ga.type = ‘text/javascript’;
ga.async = true;
ga.src = (‘https:’ ==
  document.location.protocol ? ‘https://ssl’ :
  ‘http://www’)+‘.google-analytics.com/ga.js’;
var s =
  document.getElementsByTagName(‘script’)[
  0];
s.parentNode.insertBefore(ga, s);
avoid mixed content warning
protocol relative URLs have problems
set src last
stevesouders.com/blog/2010/02/10/5a-missing-schema-double-download/
var ga = document.createElement(‘script’);
ga.type = ‘text/javascript’;
ga.async = true;
ga.src = (‘https:’ ==
  document.location.protocol ? ‘https://ssl’ :
  ‘http://www’)+‘.google-analytics.com/ga.js’;
var s =
  document.getElementsByTagName(‘script’)[
  0];
s.parentNode.insertBefore(ga, s);
previously:
   getElementsByTagName(‘head’)[0].
   appendChild(ga)
HEAD might not exist
stevesouders.com/blog/2010/05/11/appendchild-vs-insertbefore/
    Android 1.5, iPhone 3.0, Opera 8.50, Safari 3.2
stevesouders.com/blog/2010/05/12/autohead-my-first-browserscope-user-test/
var ga = document.createElement(‘script’);
ga.type = ‘text/javascript’;
ga.async = true;
ga.src = (‘https:’ ==
  document.location.protocol ? ‘https://ssl’ :
  ‘http://www’)+‘.google-analytics.com/ga.js’;
var s =
  document.getElementsByTagName(‘script’)[
  0];
s.parentNode.insertBefore(ga, s);
some browsers preserve execution order
    Firefox 3.6, Opera, OmniWeb



stevesouders.com/tests/jsorder.php
stevesouders.com/tests/jsorder.php
var ga = document.createElement(‘script’);
ga.type = ‘text/javascript’;
ga.async = true;
ga.src = (‘https:’ ==
  document.location.protocol ? ‘https://ssl’ :
  ‘http://www’)+‘.google-analytics.com/ga.js’;
var s =
  document.getElementsByTagName(‘script’)[
  0];
s.parentNode.insertBefore(ga, s);
some browsers preserve execution order
    Firefox 3.6, Opera, OmniWeb
async=true fixes this (except Opera)

stevesouders.com/tests/jsorder.php
<html>
  <head>
            A
     <link rel=stylesheet ...>
     <style>...</style>
     <script [...]></script>
            B
  </head>
  <body>
     <div>
     <p>
     <ul>
             C
  </body>
</html>

onload:      D
A




    script loads sooner
    beacon fires sooner
    blocks other async (Opera)
    may block rendering
B

    script loads later
    beacon fires later
    blocks fewer async (Opera)
    may block rendering
script loads last
    beacon fires late
    doesn’t block async
C   doesn’t block rendering
script loads after page
    beacon fires very late
    doesn’t block async
    doesn’t block rendering
    onload fires sooner
D
more
stevesouders.com/blog/2011/12/01/silk-ipad-galaxy-comparison/
stevesouders.com/mobileperf/mobileperfbkm.php
Top 100




Top 1000
takeaways
WPO                GA snippet is good
WebPagetest.org    Loadtimer.org
Cuzillion.com      MobilePerf.org
Browserscope.org   HTTPArchive.org
ControlJS.org      Velocity
localStorage       stevesouders.com
@souders
http://stevesouders.com/docs/sfjs-20120112.pptx

Mais conteúdo relacionado

Mais procurados

Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
Rob Davarnia
 

Mais procurados (20)

Beginning MEAN Stack
Beginning MEAN StackBeginning MEAN Stack
Beginning MEAN Stack
 
Java script Basic
Java script BasicJava script Basic
Java script Basic
 
MEAN Stack
MEAN StackMEAN Stack
MEAN Stack
 
Top java script frameworks ppt
Top java script frameworks pptTop java script frameworks ppt
Top java script frameworks ppt
 
The MEAN Stack
The MEAN StackThe MEAN Stack
The MEAN Stack
 
Client Vs. Server Rendering
Client Vs. Server RenderingClient Vs. Server Rendering
Client Vs. Server Rendering
 
MEAN Stack
MEAN StackMEAN Stack
MEAN Stack
 
Meanstack Introduction by Kishore Chandra
Meanstack Introduction by Kishore ChandraMeanstack Introduction by Kishore Chandra
Meanstack Introduction by Kishore Chandra
 
The MEAN stack - SoCalCodeCamp - june 29th 2014
The MEAN stack - SoCalCodeCamp - june 29th 2014The MEAN stack - SoCalCodeCamp - june 29th 2014
The MEAN stack - SoCalCodeCamp - june 29th 2014
 
Introduction to mean stack
Introduction to mean stackIntroduction to mean stack
Introduction to mean stack
 
Introduction to Javascript programming
Introduction to Javascript programmingIntroduction to Javascript programming
Introduction to Javascript programming
 
Server and client rendering of single page apps
Server and client rendering of single page appsServer and client rendering of single page apps
Server and client rendering of single page apps
 
Introduction to Java Scripting
Introduction to Java ScriptingIntroduction to Java Scripting
Introduction to Java Scripting
 
LAMP is so yesterday, MEAN is so tomorrow! :)
LAMP is so yesterday, MEAN is so tomorrow! :) LAMP is so yesterday, MEAN is so tomorrow! :)
LAMP is so yesterday, MEAN is so tomorrow! :)
 
Get MEAN! Node.js and the MEAN stack
Get MEAN!  Node.js and the MEAN stackGet MEAN!  Node.js and the MEAN stack
Get MEAN! Node.js and the MEAN stack
 
Building an E-commerce website in MEAN stack
Building an E-commerce website in MEAN stackBuilding an E-commerce website in MEAN stack
Building an E-commerce website in MEAN stack
 
FULL stack -> MEAN stack
FULL stack -> MEAN stackFULL stack -> MEAN stack
FULL stack -> MEAN stack
 
MEAN stack
MEAN stackMEAN stack
MEAN stack
 
Mean stack
Mean stackMean stack
Mean stack
 
Visual resume
Visual resumeVisual resume
Visual resume
 

Semelhante a JavaScript Perfomance

High Performance Mobile (SF/SV Web Perf)
High Performance Mobile (SF/SV Web Perf)High Performance Mobile (SF/SV Web Perf)
High Performance Mobile (SF/SV Web Perf)
Steve Souders
 
"Your script just killed my site" by Steve Souders
"Your script just killed my site" by Steve Souders"Your script just killed my site" by Steve Souders
"Your script just killed my site" by Steve Souders
Dmitry Makarchuk
 
Web Directions South - Even Faster Web Sites
Web Directions South - Even Faster Web SitesWeb Directions South - Even Faster Web Sites
Web Directions South - Even Faster Web Sites
Steve Souders
 

Semelhante a JavaScript Perfomance (20)

High Performance Mobile (SF/SV Web Perf)
High Performance Mobile (SF/SV Web Perf)High Performance Mobile (SF/SV Web Perf)
High Performance Mobile (SF/SV Web Perf)
 
Webpack
Webpack Webpack
Webpack
 
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
TDC2017 | Florianopolis - Trilha DevOps How we figured out we had a SRE team ...
 
"Your script just killed my site" by Steve Souders
"Your script just killed my site" by Steve Souders"Your script just killed my site" by Steve Souders
"Your script just killed my site" by Steve Souders
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
 
Web Directions South - Even Faster Web Sites
Web Directions South - Even Faster Web SitesWeb Directions South - Even Faster Web Sites
Web Directions South - Even Faster Web Sites
 
Website performance optimisation
Website performance optimisationWebsite performance optimisation
Website performance optimisation
 
Front End Development for Back End Java Developers - Jfokus 2020
Front End Development for Back End Java Developers - Jfokus 2020Front End Development for Back End Java Developers - Jfokus 2020
Front End Development for Back End Java Developers - Jfokus 2020
 
Webpack packing it all
Webpack packing it allWebpack packing it all
Webpack packing it all
 
Packing it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to nowPacking it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to now
 
Os mobile
Os mobileOs mobile
Os mobile
 
Os mobile
Os mobileOs mobile
Os mobile
 
Testable client side_mvc_apps_in_javascript
Testable client side_mvc_apps_in_javascriptTestable client side_mvc_apps_in_javascript
Testable client side_mvc_apps_in_javascript
 
High Performance Snippets
High Performance SnippetsHigh Performance Snippets
High Performance Snippets
 
Os mobile
Os mobileOs mobile
Os mobile
 
Build Better Responsive websites. Hrvoje Jurišić
Build Better Responsive websites. Hrvoje JurišićBuild Better Responsive websites. Hrvoje Jurišić
Build Better Responsive websites. Hrvoje Jurišić
 
The Future of CSS with Web components
The Future of CSS with Web componentsThe Future of CSS with Web components
The Future of CSS with Web components
 
The Future of CSS with Web Components
The Future of CSS with Web ComponentsThe Future of CSS with Web Components
The Future of CSS with Web Components
 
Web-Performance
Web-PerformanceWeb-Performance
Web-Performance
 
Google I/O 2012 - Protecting your user experience while integrating 3rd party...
Google I/O 2012 - Protecting your user experience while integrating 3rd party...Google I/O 2012 - Protecting your user experience while integrating 3rd party...
Google I/O 2012 - Protecting your user experience while integrating 3rd party...
 

Mais de Anatol Alizar

Mais de Anatol Alizar (20)

Cryptanalysis of the GPRS Encryption Algorithms GEA-1 and GEA-2
Cryptanalysis of the GPRS Encryption Algorithms GEA-1 and GEA-2Cryptanalysis of the GPRS Encryption Algorithms GEA-1 and GEA-2
Cryptanalysis of the GPRS Encryption Algorithms GEA-1 and GEA-2
 
Lectures on Analytic Geometry
Lectures on Analytic GeometryLectures on Analytic Geometry
Lectures on Analytic Geometry
 
Military Cryptanalytics II
Military Cryptanalytics IIMilitary Cryptanalytics II
Military Cryptanalytics II
 
Британская разведка не может нанять шпионов
Британская разведка не может нанять шпионовБританская разведка не может нанять шпионов
Британская разведка не может нанять шпионов
 
Libratus
LibratusLibratus
Libratus
 
Исковое заявление Waymo
Исковое заявление WaymoИсковое заявление Waymo
Исковое заявление Waymo
 
Решение окружного суда Северной Калифорнии
Решение окружного суда Северной КалифорнииРешение окружного суда Северной Калифорнии
Решение окружного суда Северной Калифорнии
 
Facebook обвиняют в плагиате проекта дата-центра в Швеции
Facebook обвиняют в плагиате проекта дата-центра в ШвецииFacebook обвиняют в плагиате проекта дата-центра в Швеции
Facebook обвиняют в плагиате проекта дата-центра в Швеции
 
Cloud Spanner
Cloud SpannerCloud Spanner
Cloud Spanner
 
Песочница Chrome нарушает три патента
Песочница Chrome нарушает три патентаПесочница Chrome нарушает три патента
Песочница Chrome нарушает три патента
 
Российский интернет на военном положении
Российский интернет на военном положенииРоссийский интернет на военном положении
Российский интернет на военном положении
 
Судья приказал Google выдать почту пользователя с зарубежных серверов
Судья приказал Google выдать почту пользователя с зарубежных серверовСудья приказал Google выдать почту пользователя с зарубежных серверов
Судья приказал Google выдать почту пользователя с зарубежных серверов
 
Zenimax-v-oculus-amended-complaint
Zenimax-v-oculus-amended-complaintZenimax-v-oculus-amended-complaint
Zenimax-v-oculus-amended-complaint
 
Oculus jury response
Oculus jury responseOculus jury response
Oculus jury response
 
13 млн документов ЦРУ рассекречено и опубликовано в онлайне
13 млн документов ЦРУ рассекречено и опубликовано в онлайне13 млн документов ЦРУ рассекречено и опубликовано в онлайне
13 млн документов ЦРУ рассекречено и опубликовано в онлайне
 
Тот день, когда аноны с 4chan затроллили разведывательные агентства и мировые...
Тот день, когда аноны с 4chan затроллили разведывательные агентства и мировые...Тот день, когда аноны с 4chan затроллили разведывательные агентства и мировые...
Тот день, когда аноны с 4chan затроллили разведывательные агентства и мировые...
 
В Instagram можно найти фотографии авиабилетов и присвоить себе бонусные мили
В Instagram можно найти фотографии авиабилетов и присвоить себе бонусные милиВ Instagram можно найти фотографии авиабилетов и присвоить себе бонусные мили
В Instagram можно найти фотографии авиабилетов и присвоить себе бонусные мили
 
Ещё шесть радиосигналов неизвестной природы получены из-за пределов нашей гал...
Ещё шесть радиосигналов неизвестной природы получены из-за пределов нашей гал...Ещё шесть радиосигналов неизвестной природы получены из-за пределов нашей гал...
Ещё шесть радиосигналов неизвестной природы получены из-за пределов нашей гал...
 
Рядовые сотрудники Uber использовали «режим Бога» для слежки за бывшими
Рядовые сотрудники Uber использовали «режим Бога» для слежки за бывшимиРядовые сотрудники Uber использовали «режим Бога» для слежки за бывшими
Рядовые сотрудники Uber использовали «режим Бога» для слежки за бывшими
 
Немецкий суд объяснил, почему блокировщики рекламы не нарушают закон
Немецкий суд объяснил, почему блокировщики рекламы не нарушают законНемецкий суд объяснил, почему блокировщики рекламы не нарушают закон
Немецкий суд объяснил, почему блокировщики рекламы не нарушают закон
 

Último

Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
UK Journal
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 

Último (20)

Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4j
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 

JavaScript Perfomance

  • 1. JavaScript Performance stevesouders.com/docs/sfjs-20120112.pptx Disclaimer: This content does not necessarily reflect the opinions of my employer.
  • 2. YSlow Cuzillion SpriteMe Hammerhead
  • 3. Web WPO Performance Optimization drives traffic improves UX increases revenue reduces costs
  • 4. What’s the #1 cause of slow web pages?
  • 6.
  • 7.
  • 8. all requests containing “.js” are skipped
  • 10. 1995: scripts in HEAD <head> <script src=‘a.js’></script> </head> blocks other downloads (IE 6-7, images in IE, iframes) downloaded sequentially (IE 6-7) blocks rendering during download & parse-execute
  • 11. 2007: move scripts to bottom ... <script src=‘a.js’></script> </body> doesn’t block other downloads downloaded sequentially in IE 6-7 blocks rendering during download & parse-execute
  • 12. 2009: load scripts async var se = document.createElement(‘script’) ; se.src = ‘a.js’; document.getElementsByTagName(‘he ad’)[0].appendChild(se); doesn’t block other downloads downloaded in parallel (all browsers) blocks rendering during parse-execute
  • 13. 2010: async + on-demand exec var se = new Image(); // Object se.onload = registerScript; se.src = ‘a.js’; separate download from parse-execute doesn’t block other downloads downloaded in parallel (all browsers) doesn’t block rendering until demanded
  • 15. script async & defer parsing doesn’t wait for script: • async – executed when available • defer – executed when parsing finished when is it downloaded? missing: • defer download AND execution • async/defer download, execute on demand
  • 16. 20??: markup <script src=‘a.js’ [async|defer|noexecute] [deferdownload]> doesn’t block downloads downloaded in parallel doesn’t block rendering until demanded doesn’t contend for a connection easier
  • 17. ControlJS a JavaScript module for making scripts load faster just change HTML inline & external scripts <script type=‘text/cjs’ data-cjssrc=‘main.js’> </script> <script type=‘text/cjs’> var name = getName(); </script> http://controljs.org/
  • 18. ControlJS a JavaScript module for making scripts load faster download without executing <script type=‘text/cjs’ data-cjssrc=‘main.js’ data-cjsexec=false> <script> Later if/when needed: CJS.execScript(src);
  • 19. GMail Mobile <script type=‘text/javascript’> /* var ... */ </script> get script DOM element's text remove comments eval() when invoked awesome for prefetching JS that might (not) be needed http://goo.gl/l5ZLQ
  • 23. Home screen apps on iPhone are slower because resources are re-requested even though they should be read from cache.
  • 24. localStorage window.localStorage: setItem() getItem() removeItem() clear() also sessionStorage all popular browsers, 5MB max http://dev.w3.org/html5/webstorage/ http://diveintohtml5.org/storage.html
  • 25. localStorage as cache 1st doc: write JS & CSS blocks to localStorage mres.-0yDUQJ03U8Hjija: <script>(function(){... set cookie with entries & version MRES=-0yDUQJ03U8Hjija:-4EaJoFuDoX0iloI:... later docs: read JS & CSS from localStorage document.write( localStorage.getItem(mres.- 0yDUQJ03U8Hjija) ); http://stevesouders.com/blog/2011/03/28/storager-case- study-bing-google/
  • 26. Google Analytics Async Snippet var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true; ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’)+‘.google-analytics.com/ga.js’; var s = document.getElementsByTagName(‘script’)[ 0]; s.parentNode.insertBefore(ga, s); code.google.com/apis/analytics/docs/tracking/asyncTracking.html
  • 27. var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true; ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’)+‘.google-analytics.com/ga.js’; var s = document.getElementsByTagName(‘script’)[ 0]; s.parentNode.insertBefore(ga, s); avoid mixed content warning protocol relative URLs have problems set src last stevesouders.com/blog/2010/02/10/5a-missing-schema-double-download/
  • 28. var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true; ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’)+‘.google-analytics.com/ga.js’; var s = document.getElementsByTagName(‘script’)[ 0]; s.parentNode.insertBefore(ga, s); previously: getElementsByTagName(‘head’)[0]. appendChild(ga) HEAD might not exist stevesouders.com/blog/2010/05/11/appendchild-vs-insertbefore/ Android 1.5, iPhone 3.0, Opera 8.50, Safari 3.2 stevesouders.com/blog/2010/05/12/autohead-my-first-browserscope-user-test/
  • 29. var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true; ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’)+‘.google-analytics.com/ga.js’; var s = document.getElementsByTagName(‘script’)[ 0]; s.parentNode.insertBefore(ga, s); some browsers preserve execution order Firefox 3.6, Opera, OmniWeb stevesouders.com/tests/jsorder.php
  • 31.
  • 32. var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true; ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’)+‘.google-analytics.com/ga.js’; var s = document.getElementsByTagName(‘script’)[ 0]; s.parentNode.insertBefore(ga, s); some browsers preserve execution order Firefox 3.6, Opera, OmniWeb async=true fixes this (except Opera) stevesouders.com/tests/jsorder.php
  • 33. <html> <head> A <link rel=stylesheet ...> <style>...</style> <script [...]></script> B </head> <body> <div> <p> <ul> C </body> </html> onload: D
  • 34. A script loads sooner beacon fires sooner blocks other async (Opera) may block rendering
  • 35. B script loads later beacon fires later blocks fewer async (Opera) may block rendering
  • 36. script loads last beacon fires late doesn’t block async C doesn’t block rendering
  • 37. script loads after page beacon fires very late doesn’t block async doesn’t block rendering onload fires sooner D
  • 38. more
  • 39.
  • 42.
  • 43.
  • 44.
  • 45.
  • 47.
  • 48. takeaways WPO GA snippet is good WebPagetest.org Loadtimer.org Cuzillion.com MobilePerf.org Browserscope.org HTTPArchive.org ControlJS.org Velocity localStorage stevesouders.com

Notas do Editor

  1. Permission to use photo given by Amnemona: http://www.flickr.com/photos/marinacvinhal/379111290/
  2. flickr.com/photos/bekahstargazing/318930460/
  3. flickr.com/photos/pedromourapinheiro/3123885534/
  4. http://www.flickr.com/photos/peterblapps/838125790/
  5. http://www.flickr.com/photos/salty_soul/5799650534/
  6. 3.777 seconds - http://www.webpagetest.org/result/120111_0P_2TW4Q/ - block “.js” (it’s not downloaded)5.471 seconds - http://www.webpagetest.org/result/120111_GR_2TW90/Alexa top 100wwide
  7. median: 3.650vs 2.4873.777 seconds - http://www.webpagetest.org/result/120111_0P_2TW4Q/ - block “.js” (it’s not downloaded)5.471 seconds - http://www.webpagetest.org/result/120111_GR_2TW90/Alexa top 100wwide
  8. flickr.com/photos/gevertulley/4771808965/Generallyasync &amp; defer scripts start downloading immediately. I wish they’d wait, esp. defer scripts, so they don’t hog connections from the limited pool.subatomic particle traces
  9. GMail Mobile: http://googlecode.blogspot.com/2009/09/gmail-for-mobile-html5-series-reducing.htmlSproutCore: http://blog.sproutcore.com/post/225219087/faster-loading-through-eval
  10. flickr.com/photos/bryanpearson/564703455/
  11. flickr.com/photos/bryanpearson/564703455/
  12. flickr.com/photos/nelsoncruz/431244400/
  13. block other async scripts in Operaexecute ASAPsend beacon before leaving pageblock UI thread
  14. block other async scripts in Operaexecute ASAPsend beacon before leaving pageblock UI thread
  15. block other async scripts in Operaexecute ASAPsend beacon before leaving pageblock UI thread
  16. block other async scripts in Operaexecute ASAPsend beacon before leaving pageblock UI thread
  17. flickr.com/photos/dualphoto/2609096047/
  18. flickr.com/photos/myklroventine/4062102754/