Lazy Loading Because I'm Lazy


Published on

Describes the overview process and technique of lazy loading javascript from external 3rd parties or your own in-house stuff and provides a simple example with the possible benefits for large javascript applications.

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Lazy Loading Because I'm Lazy

    1. 1. Lazy Loading“do the least work possible”
    2. 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. 3. The problem: the file keeps growing!Not scalable for large applicationsComplexity of production support increases,more code = more liability (one syntax errorand boom!)Big ball of mudHard to maintain development vs. productionsystems (dev mode with separate files, buildprocess, versioning, etc)
    4. 4. The solution: lazy loadAlways load core javascript framework(jquery + your framework/bootstrap) You don’t have aframework???Lazy load models and controllers based uponinteractionDon’t have an MVC framework? coremvc,JavascriptMVC, many othersAvoid dependency hell: keep it one-level/controller based. Don’t “abuse” prototype
    5. 5. Fine Lines Understand DOMContentLoaded and load eventsAbsolute final “End User” experience -- logsdon’t matterIt matters even for a primed cacheIt takes time to evaluate big javascript files.Caching can NEVER fix this, users see it
    6. 6. Possible improvements: why invest the time?Increase simplicity“Snappiness”, reduce memory footprintHide latencyManage user expectations (users expect towait when they do some action the firsttime, but hate waiting on every page load)Evaluate your site metrics (passers-by vs.heavy users), cache rate percentage forcost/benefit
    7. 7. Where do I start?Today (probably yesterday)Evaluate your application, especially your usersY-SLOW & Firebug Net Panel. Google Page Speed PluginLook 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. 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); } 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(, 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. 9. Desired OutcomeMinimal loading indication across mostbrowsers. “Defer” load until after load oryour custom eventGood for third party javascripts which maybe slow or trigger more blocking requeststhemselves on loadDie silently, but handle it. Don’t go on likenothing happened; don’t try to use code thatdidn’t load!
    10. 10. Example Results
    11. 11. thanks Johnathan Leppert Developer, twitter: @iamleppert Let me google that for you (further reading):