emjayess
10/10/2012 - 9:49 PM

simple async loading patterns

simple async loading patterns

// load a style
;(function(d) {
  var lnk = d.createElement('link'), h = d.getElementsByTagName('head')[0];
  lnk.href = 'css.css';
  lnk.type = 'text/css';
  lnk.rel = 'stylesheet';
  h.appendChild(lnk);
}​(document))​​​​;
// iframe (dynamic async)
// http://www.aaronpeters.nl/blog/iframe-loading-techniques-performance
;(function(d) {
  var iframe = d.body.appendChild(d.createElement('iframe'));
  var idoc = iframe.contentWindow.document;

  if ('srcdoc' in iframe) {
    // write to the 'srcdoc' attribute
  }
  // or
  idoc.open().write('<body onload="' +
                    'var d = document;d.getElementsByTagName(\'head\')[0].' +
                    'appendChild(d.createElement(\'script\')).src' +
                    '=\'\/path\/to\/file\'">');
      
  idoc.close(); //iframe onload event fires
}​(document));

// see also: http://calendar.perfplanet.com/2010/fast-ads-with-html5/
// for srcdoc and seamless attributes
function supports_srcdoc() {
  return 'srcdoc' in document.createElement('iframe');
}

// srcdoc polyfill: https://github.com/jugglinmike/srcdoc-polyfill/
​
// load a script
;(function(d) {
  var js = d.createElement('script'), h = d.getElementsByTagName('head')[0];
  js.src = 'js.js'; 
  h.appendChild(js);
}(document));