pre.js
Use pre.js to load your JS and CSS files efficiently. Perfect for mobile apps
and sites where 3G can often fail.
- Petite: only 2.5kb gzipped.
- Resilient: Auto-retries downloads when they fail.
- Efficient: Downloads files in parallel.
Pre()
.retries(10)
.css('/assets/app.css')
.js('http://www.google.com/jsapi', function() { return window.google; })
.js('/assets/app.js', function() { return window.App; })
.then({
App.start();
});
Usage
Via NPM
npm install --save pre-js
Via bower
bower install pre-js
Manual
Download index.min.js.
Recommended use
Create a file like load.js, which contains pre.js and your loader code.
Use whatever build tool you prefer to do this for you. This gets you a small
<4kb loader you can use as a "gateway" to the rest of your app.
With Webpack or Browserify, it probably will be like this:
var Pre = require('pre-js');
Pre()
.css('/assets/app.css')
.js ('/assets/vendor.js', function() { return window.jQuery; })
.js ('/assets/app.js', function() { return window.App; })
.then({
App.start();
});
API reference
See pre.js's inline comments for more info. Here's a quick reference of the
API:
Pre()
.retries(10)
.js('/assets/jquery.js', function() { return window.jQuery; })
.js('http://www.google.com/jsapi', function() { return window.google; })
.js('/vendor.js', function() { return window.jQuery; })
.js('/app.js', function() { return window.App; })
.then(function() {
google.api.load('maps');
App.start();
})
.css('http://google.com/fonts?f=Roboto:300')
.css('/assets/application.css')
.asset('/assets/image.jpg')
.asset('/assets/font.woff')
.on('progress', function(e) {
document.getElementById('progress').style.width = '' + e.percent*100 + '%';
console.log("Loaded %s (%s of %s files loaded)", e.file, e.loaded, e.total);
})
.on('retry', function (e) {
console.warn("Failed to fetch %s, retrying", e.uri);
})
.on('fail', function (e) {
console.warn("Failed to load %s", e.uri);
})
.if(condition, function (pre) {
pre.js('...');
})
Conditional loading
Simple:
Pre()
.js(window.JSON || 'json2.js',
function() { return window.JSON; })
.js(oldie ? 'jquery-1.9.js' : 'jquery-2.1.js',
function() { return window.jQuery; })
For more complicated things:
Pre()
.if(env === 'development', function (pre) {
pre
.js('livereload.js')
.js('weinre.js')
})
CoffeeScript
Better with CoffeeScript, if that's your thing:
Pre()
.css 'style.css'
.js 'jquery.js', -> jQuery?
.js 'app.js', -> App?
.then -> App.start()
Acknowledgements
Implemented on top of yepnope.js. In fact, it includes
yepnope.js.
MIT.