asynz
v0.2.1
Published
Hipster way of load async scripts in the browser
Downloads
3
Readme
asynz
Hipster way of load async script in the browser
Just a tiny module to load scripts in the browser. It also has support for script attributes and cache.
Install
$ npm i asynz
$ bower i asynz
### Example: loading a dynamic library
import asynz from "asynz";
const src = 'https://code.jquery.com/jquery-2.2.1.js';
loadLibrary(src);
async loadLibrary() {
console.log(typeof window.jQuery === "undefined");
let script = await asynz(src);
$('body').html('jQuery is now available');
}
### Passing attributes
const src = 'https://code.jquery.com/jquery-2.2.1.js';
const attrs = {
id: 'jquery',
async: true,
defer: true,
foo: 'bar',
'data-api-key': 123
};
let script = await asynz(src, attrs);
console.log($('#jquery').attr('data-api-key') === 123);
Notice that when you pass script
properties like async or defer, azync won't add them as an attribute, instead will set the value directly to the script, e.g. script.async === true
Error handling
One of the cool things of the async functions, is that you can handle errors like it was synchronous code.
const erroredSrc = 'http://foourl';
try {
await asynz(erroredSrc);
// Do stuff
} catch(e) {
console.log('Error :(', e);
}
### Promise style You can also use Promise style if you prefer
import asynz from "asynz"
const src = 'https://code.jquery.com/jquery-2.2.1.js';
asynz(src).then(script => {
console.log(jQuery);
}).catch(console.log.bind(console));
Miscellaneous
In order to use async functions today you will need to install/include some stuff in your build process
Needed packages
$ npm i babel-cli babel-polyfill babel-plugin-transform-async-to-generator babel-preset-es2015 babel-preset-stage-0 --save-dev
.babelrc
{
"presets": ["es2015", "stage-0"],
"plugins": ["transform-async-to-generator"]
}
Include in your source
require("babel-core/register");
require("babel-polyfill");