Very simple promise based script loader and JSONP
import simpleLoadScript from 'simple-load-script';
try {
const scriptRef = await simpleLoadScript(
'https://code.jquery.com/jquery-3.7.1.min.js',
);
console.log(scriptRef); // HTMLScriptElement
} catch (err) {
console.log(err);
}
import simpleLoadScript from 'simple-load-script';
simpleLoadScript('https://code.jquery.com/jquery-3.7.1.min.js')
.then(function (scriptRef) {
console.log(scriptRef); // HTMLScriptElement
})
.catch(function (err) {
console.log(err);
});
import simpleLoadScript from 'simple-load-script';
try {
const scriptRef = await simpleLoadScript({
url: 'https://code.jquery.com/jquery-3.7.1.min.js',
inBody: true,
attrs: { id: 'one', charset: 'UTF-8' },
});
console.log(scriptRef); // HTMLScriptElement inBody with attrs present
} catch (err) {
console.log(err);
}
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);
}
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);
}
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,
},
'https://code.jquery.com/jquery-3.7.1.min.js',
]);
console.log(scriptRefs); // HTMLScriptElement[]
} catch (err) {
console.log(err);
}
Config | string | (Config | string)[]
interface Config {
url: string;
attrs?: Record<string, string>;
inBody?: boolean;
insertInto?: string | null;
removeScript?: boolean;
}
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
Check files or package.json
- uses addEventListener, Array.isArray, for…of, destructuring Promise & Promise.all