Blog2014 ≫ Post loading javascript

Experimenting with loading javascript after the page has loaded for speed (as mentioned the other day) and I have extended the plan I had the other day. I have this repeating pattern where I am wrapping each piece of js in a self invoking anonymous function, and then adding in a check for other dependencies before executing the code. I'm writing this by hand every time, which is daft, so I'm thinking of detecting something like this in the source of the page:

<script src="foo.js" requires="bar,etc" />

and then grabbing the source of that and rewriting it as

!function ( ) {
 var = init ( ) {
   // original script goes here
 };
  var i = setInterval( function ( ) {
   if ( ! ( window.foo && window.bar )) return;
   clearInterval( i );
   init( );
 }, 10 );
}( );

Good pattern? Bad pattern? I'm not sure...

I'm also stripping all of the css out of the page now and loading it at the end like this:

( function ( stylesheets ) {
  var callback = function ( ) {
    for(l=stylesheets.length,i=0;i<l;i++){
      var e=d.createElement('link');
      e.href=stylesheets[i];
      e.rel='stylesheet';
      var h=d.getElementsByTagName('head')[0].firstChild;
      h.parentNode.insertBefore(e,h);
    }
  };
  if ( typeof requestAnimationFrame === 'undefined' ) requestAnimationFrame = null;
  if ( typeof webkitRequestAnimationFrame === 'undefined' ) webkitRequestAnimationFrame = null;
  if ( typeof mozRequestAnimationFrame === 'undefined' ) mozRequestAnimationFrame = null;
  if ( typeof msRequestAnimationFrame === 'undefined' ) msRequestAnimationFrame = null;
  r = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame;
  if (r) return r(callback);
  callback( );
} ( [ '/css/foo.css', '/css/bar.css' ] ));

see the source of this page for more... It's a variation on the code recommended here, adapted to work better in older mobile browsers, and as you can see I'm doing ok for page speed score.

UPDATE: again quite old I don't use this code any more! I think webpack and things overtook me on the dependencies. But this is a few years ago now...

javascript: Programming language of the internets, mostly how I make my living.

⬅️ :: ➡️

Paul Clarke's weblog - I live in A small town. Wed and dad to two, I'm a full stack web developr, and I do mostly js / Node, some ruby, python, php ect ect. I like pubs, parkrun, eating, home-automation and other diy stuff, history, genealogy, Television, squirrels, pirates, lego, and TIME TRAVEL.