simple-load-script
v2.0.0
Published
Very simple promise based script and JSONP
Downloads
20,598
Readme
simple-load-script
Very simple promise based script loader and JSONP
Usage
Async/await
import simpleLoadScript from 'simple-load-script';
try {
const scriptRef = await simpleLoadScript('//code.jquery.com/jquery-2.2.3.js');
console.log(scriptRef); // HTMLScriptElement
} catch (err) {
console.log(err);
}
Promise
import simpleLoadScript from 'simple-load-script';
simpleLoadScript('//code.jquery.com/jquery-2.2.3.js')
.then(function (scriptRef) {
console.log(scriptRef);
})
.catch(function (err) {
console.log(err);
});
Config object
import simpleLoadScript from 'simple-load-script';
try {
const scriptRef = await simpleLoadScript({
url: '//code.jquery.com/jquery-2.2.3.js',
inBody: true,
attrs: { id: 'one', charset: 'UTF-8' },
});
console.log(scriptRef); // HTMLScriptElement inBody with attrs present
} catch (err) {
console.log(err);
}
Google Maps API
Runs global callback (window.gmapiready)
import simpleLoadScript from 'simple-load-script';
try {
const scriptRef = await simpleLoadScript('//maps.googleapis.com/maps/api/js?&callback=gmapiready');
console.log(scriptRef); // HTMLScriptElement
} catch (err) {
console.log(err);
}
JSONP
Runs global callback (window.elo)
var simpleLoadScript = require('simple-load-script');
try {
const scriptRef = await simpleLoadScript({
url: '//api.ipinfodb.com/v3/ip-city/?format=json&callback=elo',
removeScript: true,
});
console.log(scriptRef); // undefined
} catch (err) {
console.log(err);
}
Array mode - objects and urls, callBackNames must have unique names
import simpleLoadScript from 'simple-load-script';
try {
const scriptRefs = await simpleLoadScript([
'//maps.googleapis.com/maps/api/js?&callback=gmapiready',
{
url: '//api.ipinfodb.com/v3/ip-city/?format=json&callback=elo',
removeScript: true,
},
'//code.jquery.com/jquery-2.2.3.js',
]);
console.log(scriptRefs); // HTMLScriptElement[]
} catch (err) {
console.log(err);
}
Arguments
Config | string | (Config | string)[]
Config
Interface
interface Config {
url: string;
attrs?: Record<string, string>;
inBody?: boolean;
insertInto?: string | null;
removeScript?: boolean;
}
Default values
const defaultConfig = {
url: '',
attrs: {},
inBody: false,
insertInto: null,
removeScript: false,
};
url
- file to append to bodyattrs
- with attributes to append to script tag (charset
,type
,id
, …)inBody
- append todocument.body
instead ofdocument.head
insertInto
- CSS selector (an ID, class name, element name, etc.) to insert the script into. OverridesinBody
value.removeScript
- remove script tag after load; it's always removed on an error
Specific import
Check files or package.json
Changelog
Misc.
- uses addEventListener, Array.isArray, for…of, destructuring Promise & Promise.all