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

More Related Content

PDF
JavaScript Promise
PPTX
Avoiding callback hell in Node js using promises
PPTX
Promises, Promises
PDF
Promise pattern
PDF
$q and Promises in AngularJS
PPTX
JavaScript Promises
PDF
JavaScript Promises
PDF
The evolution of asynchronous javascript
JavaScript Promise
Avoiding callback hell in Node js using promises
Promises, Promises
Promise pattern
$q and Promises in AngularJS
JavaScript Promises
JavaScript Promises
The evolution of asynchronous javascript

What's hot (20)

PDF
The Open Web and what it means
PDF
Javascript Frameworks for Joomla
PDF
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
PDF
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
PPTX
The Promised Land (in Angular)
PDF
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
PDF
Realm.io par Clement Sauvage
PDF
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
PDF
The Beauty Of Java Script V5a
PPTX
ES6 is Nigh
PDF
HTML,CSS Next
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
PDF
Web Crawling with NodeJS
PDF
JavaScript promise
PDF
Boom! Promises/A+ Was Born
PPTX
Getting Reactive with Cycle.js and xstream
PDF
¿Cómo de sexy puede hacer Backbone mi código?
PPTX
Testable, Object-Oriented JavaScript
PDF
The Beauty of Java Script
PPTX
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
The Open Web and what it means
Javascript Frameworks for Joomla
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
The Promised Land (in Angular)
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
Realm.io par Clement Sauvage
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
The Beauty Of Java Script V5a
ES6 is Nigh
HTML,CSS Next
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Web Crawling with NodeJS
JavaScript promise
Boom! Promises/A+ Was Born
Getting Reactive with Cycle.js and xstream
¿Cómo de sexy puede hacer Backbone mi código?
Testable, Object-Oriented JavaScript
The Beauty of Java Script
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Ad

Viewers also liked (19)

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

Similar to Lazy Loading Because I'm Lazy (20)

PPTX
JavaScript Performance Patterns
PPTX
JavaScript performance patterns
PPT
Fast Loading JavaScript
PDF
Performance on the Yahoo! Homepage
PDF
Performance patterns
KEY
Lazy load Everything!
PDF
Building performance into the new yahoo homepage presentation
PDF
Embracing Async with Deferreds and Promises
PPT
Even Faster Web Sites at jQuery Conference '09
PDF
Developing High Performance Web Apps
KEY
Developing High Performance Web Apps - CodeMash 2011
PPTX
Smart tag loading Script loading case study 2011
PPTX
JavaScript Performance (at SFJS)
PPTX
JavaScript Perfomance
PDF
Js Saturday 2013 your jQuery could perform better
PPT
Building fast webapps, fast - Velocity 2010
ZIP
On Demand Javascript - Scalecamp 2009
PDF
High Performance JavaScript - Fronteers 2010
PDF
High Performance JavaScript (Amazon DevCon 2011)
ODP
Web program-peformance-optimization
JavaScript Performance Patterns
JavaScript performance patterns
Fast Loading JavaScript
Performance on the Yahoo! Homepage
Performance patterns
Lazy load Everything!
Building performance into the new yahoo homepage presentation
Embracing Async with Deferreds and Promises
Even Faster Web Sites at jQuery Conference '09
Developing High Performance Web Apps
Developing High Performance Web Apps - CodeMash 2011
Smart tag loading Script loading case study 2011
JavaScript Performance (at SFJS)
JavaScript Perfomance
Js Saturday 2013 your jQuery could perform better
Building fast webapps, fast - Velocity 2010
On Demand Javascript - Scalecamp 2009
High Performance JavaScript - Fronteers 2010
High Performance JavaScript (Amazon DevCon 2011)
Web program-peformance-optimization

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Encapsulation theory and applications.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
A Presentation on Artificial Intelligence
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
The AUB Centre for AI in Media Proposal.docx
Unlocking AI with Model Context Protocol (MCP)
Assigned Numbers - 2025 - Bluetooth® Document
MYSQL Presentation for SQL database connectivity
sap open course for s4hana steps from ECC to s4
Network Security Unit 5.pdf for BCA BBA.
Dropbox Q2 2025 Financial Results & Investor Presentation
Programs and apps: productivity, graphics, security and other tools
Agricultural_Statistics_at_a_Glance_2022_0.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Encapsulation theory and applications.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
A Presentation on Artificial Intelligence
Mobile App Security Testing_ A Comprehensive Guide.pdf
Digital-Transformation-Roadmap-for-Companies.pptx

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/

Editor's Notes