Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Lazy Load Everything!

Lazy Load Everything!

Talk given at Web Directions South, Sydney - October 2012

Sebastiano Armeli

October 18, 2012
Tweet

More Decks by Sebastiano Armeli

Other Decks in Programming

Transcript

  1. • Asynchronous calls • Load on-demand LAZY LOADING • window

    ‘onload’ NOT delayed • Driven by Events Monday, 3 June 13
  2. <body> <!-- Page content --> <img .../> <!--JS concatenated, at

    the bottom--> <script src=”js/one.min.js”></script> </body> Concatenation Monday, 3 June 13
  3. DRAWBACKS • No parallel downloads • Limit bene!ts from caching

    • Limit bene!ts from CDN • ‘DOMContentLoaded’ still late Monday, 3 June 13
  4. var g = document.createElement('script'); g.type = 'text/javascript'; g.async = true;

    g.src = 'js/third_party.js'; var s = document. getElementsByTagName('script')[0]; s.parentNode.insertBefore(g, s); Dynamic <script> Monday, 3 June 13
  5. $(window).load(function(){ // Async insert <script> var g = document.createElement('script'); g.type

    = 'text/javascript'; g.async = true; g.src = 'js/third_party.js'; var s = document. getElementsByTagName('script')[0]; s.parentNode.insertBefore(g, s); }); Async + Event-driven Monday, 3 June 13
  6. • Dependecy Management • Intuitive methods to load JS SCRIPT

    LOADERS • Parallel downloads Monday, 3 June 13
  7. function loadVisible(el, script, callback) { var rect = el.getBoundingClientRect(); if

    (rect.top >= 0 && rect.left >= 0 && rect.bottom <= window.innerHeight && rect.right <= window.innerWidth) { // Load the script yepnope.injectJs(script, function(){ if (callback) { callback(); } }); } } Monday, 3 June 13
  8. JAIL.js • jQuery plugin by @sebarmeli • Easy to use

    -> $(‘img’).jail() • ‘data-src’ attribute • A few con!gurations available Monday, 3 June 13
  9. // Images loaded scrolling down $(function(){ $(‘img’).jail(); }); // Images

    loaded after an event $(function(){ $(‘img’).jail({ triggerElement: ‘a.link’, event: ‘click’ }); }); Monday, 3 June 13