SlideShare une entreprise Scribd logo
1  sur  11
Lazy Loading
“do the least work possible”
Evolution of javascript application
           optimization

 <head> <script> code </script> </head>

 Many separate script file as separate
 resources (cacheable)

 Far futures expires headers, e-tags

 Reduce requests: minification and
 concatenation

 Serve from static, “cookieless” domains, CDNs

 We’re still slow....what’s next?
The problem: the file
   keeps growing!
Not scalable for large applications

Complexity of production support increases,
more code = more liability (one syntax error
and boom!)

Big ball of mud

Hard to maintain development vs. production
systems (dev mode with separate files, build
process, versioning, etc)
The solution: lazy load
Always load core javascript framework
(jquery + your framework/bootstrap)  You don’t have a
framework???




Lazy load models and controllers based upon
interaction

Don’t have an MVC framework? coremvc,
JavascriptMVC, many others

Avoid dependency hell: keep it one-level/
controller based. Don’t “abuse” prototype
Fine Lines
              Understand
    DOMContentLoaded and load events
Absolute final “End User” experience. DOMContentLoaded = DOM is
ready, loaded. load = all page components have finished loading

It matters even for a primed cache, big/many javascript
components delay final onload event, causing loading/blocking

It takes time to parse & evaluate big javascript files. Caching can’t
fix this, users see it
Possible improvements:
 why invest the time?
Increase simplicity

“Snappiness”, reduce memory footprint --
less code in memory

Hide latency

Manage user expectations (users expect to
wait when they do some action the first
time, but hate waiting on every page load)

Evaluate your site metrics (passers-by vs.
heavy users), cache rate percentage for
Where do I start?
Today (probably yesterday)

Evaluate your application, especially your users

Y-SLOW & Firebug Net Panel. Google Page Speed Plugin

Look at existing solutions

    jquery plugins available

    yuiloader, requirejs, many others as well

    dojo loader & dep management

    (maybe) do your own - simple bootstrap with simple API

    test in all target browsers for loading indications. hacks will be
    needed
<html>
      A maybe-contrived example
<head>
<title>LazyLoading Test</title>
<script>
         var AsyncLoader = function(src, cb) {
         var s = document.createElement('script');
         s.type = 'text/javascript';
                             s.async = true;
                             s.src = src + '?=' + Math.random(); // make sure we are loading this once
                             if(typeof(cb) == 'function') {
                                       this.onLoad(cb);
                             }



                                                                                                  https://gist.github.com/904251
                             var onLoad = this.onLoad();

                                     s.onreadystatechange = function() {
                                              if(this.readyState == 'loaded' ||
                                                         this.readyState == 'complete') {
                                                         onLoad();
                                              }
                                     };
                                     s.onload = onLoad;
                                     s.onerror = onLoad;

                            var asyncLoad = function() {
                                    setTimeout(function() {
                                              document.getElementById('msg').innerHTML = document.getElementById('msg').innerHTML + 'Loading...';
                                              var x = document.getElementsByTagName('script')[0];
                                              var head = document.getElementsByTagName("head")[0];
                                              x.parentNode.insertBefore(s, x);
                                    }, 1000);
                            };

                            if (window.attachEvent) {
                                       window.attachEvent('onload', asyncLoad);
                            } else if(window.addEventListener) {
                                       window.addEventListener('load', asyncLoad, false);
                            }
         };

         AsyncLoader.prototype.onLoad = function(cb) {
                if(typeof(cb) == 'function') {
                           this._cb = cb;
                } else if(typeof(this._cb) == 'function') {
                           var that = this;
                           return function() {
                                     that._cb();
                           }
                }
         };

         var loader = new AsyncLoader('http://www.mersenneforum.org/txt/43.txt', function() {
                  document.getElementById('msg').innerHTML = document.getElementById('msg').innerHTML + 'done';
         });

</script>
</head>
<body>
<h1>Javascript Lazy Loading Test</h1>
<div id='msg'></div>
<div style="height:1000px; width: 50px; background: #aaaaaa;"></div>
</body>
</html>
Desired Outcome
Minimal loading indication across most
browsers. “Defer” load until after load or
your custom event

Good for third party javascripts which may
be slow or trigger more blocking requests
themselves which continue page loading

Die silently, but handle it. Don’t go on like
nothing happened; don’t try to use code that
didn’t load!
Example Results


http://www.letseehere.com/examples/lazy_loading/
thanks
                   Johnathan Leppert
                  Developer, Manta.com
                  twitter: @iamleppert
              johnathan.leppert@gmail.com
               Let me google that for you
                    (further reading):
https://gist.github.com/904251
http://velocityconf.com/velocity2010/public/schedule/detail/15412
http://ajaxpatterns.org/On-Demand_Javascript
http://jasonleveille.com/blog/2008/05/javascript-lazy-loading
http://developer.yahoo.com/yui/3/yui/
http://requirejs.org
http://wonko.com/post/painless_javascript_lazy_loading_with_lazyload
http://ajaxian.com/archives/a-technique-for-lazy-script-loading
http://www.digital-web.com/articles/improve_page_performance_with_lazy_loading/

Contenu connexe

Tendances

The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it means
Robert Nyman
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
Luke Summerfield
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, ChileJavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos AiresJavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, MontevideoJavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
Robert Nyman
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
Domenic Denicola
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Jon Kruger
 

Tendances (20)

The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it means
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, ChileJavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
 
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos AiresJavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, MontevideoJavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement Sauvage
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
HTML,CSS Next
HTML,CSS NextHTML,CSS Next
HTML,CSS Next
 
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...
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJS
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
Getting Reactive with Cycle.js and xstream
Getting Reactive with Cycle.js and xstreamGetting Reactive with Cycle.js and xstream
Getting Reactive with Cycle.js and xstream
 
¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?¿Cómo de sexy puede hacer Backbone mi código?
¿Cómo de sexy puede hacer Backbone mi código?
 
Testable, Object-Oriented JavaScript
Testable, Object-Oriented JavaScriptTestable, Object-Oriented JavaScript
Testable, Object-Oriented JavaScript
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
 

En vedette

Art Salon @ SENI
Art Salon @ SENIArt Salon @ SENI
Art Salon @ SENI
KC Y
 
Seo by jamal
Seo by jamalSeo by jamal
Seo by jamal
Magsnet
 
мп стратегия достижения вашего успеха
мп стратегия достижения вашего успехамп стратегия достижения вашего успеха
мп стратегия достижения вашего успеха
sherif
 
บทเรียน เรื่อง คำกริยา ป.5
บทเรียน เรื่อง คำกริยา ป.5บทเรียน เรื่อง คำกริยา ป.5
บทเรียน เรื่อง คำกริยา ป.5
ปวริศา
 

En vedette (19)

UX Psychology 1st Track.
UX Psychology 1st Track.UX Psychology 1st Track.
UX Psychology 1st Track.
 
I18n
I18nI18n
I18n
 
การโพสต์รูปในเว็บFlickr
การโพสต์รูปในเว็บFlickrการโพสต์รูปในเว็บFlickr
การโพสต์รูปในเว็บFlickr
 
Art Salon @ SENI
Art Salon @ SENIArt Salon @ SENI
Art Salon @ SENI
 
EQUUSTUR
EQUUSTUR EQUUSTUR
EQUUSTUR
 
Jenny Ekmark En förstudie hur Skogrand skyltdesign kan positionera sig på nätet
Jenny Ekmark En förstudie hur Skogrand skyltdesign kan positionera sig på nätetJenny Ekmark En förstudie hur Skogrand skyltdesign kan positionera sig på nätet
Jenny Ekmark En förstudie hur Skogrand skyltdesign kan positionera sig på nätet
 
DE VINS
DE VINSDE VINS
DE VINS
 
Bilaga 1 3 Adhdkvinnor
Bilaga 1 3 AdhdkvinnorBilaga 1 3 Adhdkvinnor
Bilaga 1 3 Adhdkvinnor
 
SALTRA BANDA
SALTRA BANDASALTRA BANDA
SALTRA BANDA
 
Lea PåLsson Knm08 Slutprojekt adhdkvinnor.se
Lea PåLsson Knm08 Slutprojekt adhdkvinnor.seLea PåLsson Knm08 Slutprojekt adhdkvinnor.se
Lea PåLsson Knm08 Slutprojekt adhdkvinnor.se
 
Seo by jamal
Seo by jamalSeo by jamal
Seo by jamal
 
Ministry Presentation
Ministry PresentationMinistry Presentation
Ministry Presentation
 
UX Psychology 2nd Track.
UX Psychology 2nd Track.UX Psychology 2nd Track.
UX Psychology 2nd Track.
 
¿Qué es la ley de la oferta y la demanda
¿Qué es la ley de la oferta y la demanda¿Qué es la ley de la oferta y la demanda
¿Qué es la ley de la oferta y la demanda
 
Mp ru 2012
Mp ru 2012Mp ru 2012
Mp ru 2012
 
мп стратегия достижения вашего успеха
мп стратегия достижения вашего успехамп стратегия достижения вашего успеха
мп стратегия достижения вашего успеха
 
เทคโนโลยี Web 2
เทคโนโลยี Web 2เทคโนโลยี Web 2
เทคโนโลยี Web 2
 
Fpt Tesi Scavenging Definitiva
Fpt Tesi Scavenging DefinitivaFpt Tesi Scavenging Definitiva
Fpt Tesi Scavenging Definitiva
 
บทเรียน เรื่อง คำกริยา ป.5
บทเรียน เรื่อง คำกริยา ป.5บทเรียน เรื่อง คำกริยา ป.5
บทเรียน เรื่อง คำกริยา ป.5
 

Similaire à Lazy Loading Because I'm Lazy

Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
Designing a JavaFX Mobile application
Designing a JavaFX Mobile applicationDesigning a JavaFX Mobile application
Designing a JavaFX Mobile application
Fabrizio Giudici
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
IndicThreads
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
vhazrati
 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
Robert Nyman
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
 

Similaire à Lazy Loading Because I'm Lazy (20)

Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
 
Designing a JavaFX Mobile application
Designing a JavaFX Mobile applicationDesigning a JavaFX Mobile application
Designing a JavaFX Mobile application
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfaces
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Alert
AlertAlert
Alert
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 
NodeJS
NodeJSNodeJS
NodeJS
 

Dernier

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Dernier (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 

Lazy Loading Because I'm Lazy

  • 1. Lazy Loading “do the least work possible”
  • 2. Evolution of javascript application optimization <head> <script> code </script> </head> Many separate script file as separate resources (cacheable) Far futures expires headers, e-tags Reduce requests: minification and concatenation Serve from static, “cookieless” domains, CDNs We’re still slow....what’s next?
  • 3. The problem: the file keeps growing! Not scalable for large applications Complexity of production support increases, more code = more liability (one syntax error and boom!) Big ball of mud Hard to maintain development vs. production systems (dev mode with separate files, build process, versioning, etc)
  • 4. The solution: lazy load Always load core javascript framework (jquery + your framework/bootstrap) You don’t have a framework??? Lazy load models and controllers based upon interaction Don’t have an MVC framework? coremvc, JavascriptMVC, many others Avoid dependency hell: keep it one-level/ controller based. Don’t “abuse” prototype
  • 5. Fine Lines Understand DOMContentLoaded and load events Absolute final “End User” experience. DOMContentLoaded = DOM is ready, loaded. load = all page components have finished loading It matters even for a primed cache, big/many javascript components delay final onload event, causing loading/blocking It takes time to parse & evaluate big javascript files. Caching can’t fix this, users see it
  • 6. Possible improvements: why invest the time? Increase simplicity “Snappiness”, reduce memory footprint -- less code in memory Hide latency Manage user expectations (users expect to wait when they do some action the first time, but hate waiting on every page load) Evaluate your site metrics (passers-by vs. heavy users), cache rate percentage for
  • 7. Where do I start? Today (probably yesterday) Evaluate your application, especially your users Y-SLOW & Firebug Net Panel. Google Page Speed Plugin Look at existing solutions jquery plugins available yuiloader, requirejs, many others as well dojo loader & dep management (maybe) do your own - simple bootstrap with simple API test in all target browsers for loading indications. hacks will be needed
  • 8. <html> A maybe-contrived example <head> <title>LazyLoading Test</title> <script> var AsyncLoader = function(src, cb) { var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = src + '?=' + Math.random(); // make sure we are loading this once if(typeof(cb) == 'function') { this.onLoad(cb); } https://gist.github.com/904251 var onLoad = this.onLoad(); s.onreadystatechange = function() { if(this.readyState == 'loaded' || this.readyState == 'complete') { onLoad(); } }; s.onload = onLoad; s.onerror = onLoad; var asyncLoad = function() { setTimeout(function() { document.getElementById('msg').innerHTML = document.getElementById('msg').innerHTML + 'Loading...'; var x = document.getElementsByTagName('script')[0]; var head = document.getElementsByTagName("head")[0]; x.parentNode.insertBefore(s, x); }, 1000); }; if (window.attachEvent) { window.attachEvent('onload', asyncLoad); } else if(window.addEventListener) { window.addEventListener('load', asyncLoad, false); } }; AsyncLoader.prototype.onLoad = function(cb) { if(typeof(cb) == 'function') { this._cb = cb; } else if(typeof(this._cb) == 'function') { var that = this; return function() { that._cb(); } } }; var loader = new AsyncLoader('http://www.mersenneforum.org/txt/43.txt', function() { document.getElementById('msg').innerHTML = document.getElementById('msg').innerHTML + 'done'; }); </script> </head> <body> <h1>Javascript Lazy Loading Test</h1> <div id='msg'></div> <div style="height:1000px; width: 50px; background: #aaaaaa;"></div> </body> </html>
  • 9. Desired Outcome Minimal loading indication across most browsers. “Defer” load until after load or your custom event Good for third party javascripts which may be slow or trigger more blocking requests themselves which continue page loading Die silently, but handle it. Don’t go on like nothing happened; don’t try to use code that didn’t load!
  • 11. thanks Johnathan Leppert Developer, Manta.com twitter: @iamleppert johnathan.leppert@gmail.com Let me google that for you (further reading): https://gist.github.com/904251 http://velocityconf.com/velocity2010/public/schedule/detail/15412 http://ajaxpatterns.org/On-Demand_Javascript http://jasonleveille.com/blog/2008/05/javascript-lazy-loading http://developer.yahoo.com/yui/3/yui/ http://requirejs.org http://wonko.com/post/painless_javascript_lazy_loading_with_lazyload http://ajaxian.com/archives/a-technique-for-lazy-script-loading http://www.digital-web.com/articles/improve_page_performance_with_lazy_loading/

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n