inject.js is a < 1 kb (minified) asynchronous resource loader with callback functions.
Why another ressource loader?
For my last project I decided to use yepnope, a conditional ressource loader. Yepnope is very powerfull and has all the features I need to progressively enhance the user experience. And it is already included in modernizr. The only drawback it has, is an issue with older mobile OSs like iOS 4.x and Android 2.3.x and below. As Android 2.3.x market share is still very high it was a no go for me.
So I needed my own resource loader and had to make some decisions on it’s features. First of all, leaving things out is very tough. Even for me as a pragmatic and minimalistic fellow. But the result has to be flexible, integrable and only at a few bytes.
Essential features:
- I don’t want to block the rendering of the page with javascript files, so I need dynamic script injections
- some scripts require a init or a DOM-Element as input so I need callback functions
Drop-outs:
- my javascript files do not depend on code from other files so I don’t need modules, parallel downloading and in order execution of scripts
- I have only few conditions like has touch support, screen width and is a apple device so I don’t need build in conditions
The result is inject.js, an asynchronous resource loader with callback functions.
What does inject.js do?
inject.js takes a path to a javascript or css file and a optional callback. It adds this file async to the page and calls the callback when the file has loaded. No more, no less.
How to use it?
// load and execute single script
inject.js('/path/to/file.js');
// load single css file
inject.css('/path/to/file.css');
// load a script and execute a function after it has been loaded
inject.js('/path/to/file.js', function() {
console.log('file.js has loaded');
});
// load a css file and execute a function after it has been loaded
inject.css('/path/to/file.css',function(){
console.log('file.css has loaded');
});
How to support Conditions?
As I had to leave out build-in conditions I have use them native. Quite pragmatic, isn’t it?
// check for touch events support, aka: it's very likely to be a touch device
if (Modernizr.touch) {
inject.js('/path/to/touch.js');
inject.css('/path/to/touch.css');
}
// check for screen width
if (window.screen.width > 768) {
inject.js('/path/to/desktop.js');
inject.css('/path/to/desktop.css');
}
// check for apple device
if ( /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1 ){
inject.js('/path/to/ios.js');
}
Conclusion
The minified version of inject.js is less than 1 kb which is quite perfect for mobile first websites. I can easily inject resources in a self explaining way without blocking the rendering of the page. I think I am a lucky guy.