The ResourceInjector is a utility for dynamically loading JavaScript and CSS resources into a webpage. It helps developers ensure that external scripts and stylesheets are loaded only once, providing a caching mechanism through a static 'loadedResources' map. The 'loadScript' and 'loadStyle' methods handle injecting 'script' and 'link' elements, respectively, into the DOM, while also managing potential load timeouts.
600B gzipped
➤ Install
$ yarn add resource-injector
➤ Import
import ResourceInjector from 'resource-injector';
➤ Usage
import ResourceInjector from 'resource-injector';
const injector = new ResourceInjector();
// Load a JavaScript resource
injector
.loadResource({
url: 'https://example.com/script.js',
type: 'script',
options: { async: true },
timeout: 5000,
forceReload: true,
})
.then(() => console.log('Script loaded successfully'))
.catch(() => console.error('Failed to load script'));
// Load a CSS resource
injector
.loadResource({
url: 'https://example.com/styles.css',
type: 'style',
timeout: 7000,
})
.then(() => console.log('Style loaded successfully'))
.catch(() => console.error('Failed to load style'));
➤ Options
Option | Type | Default | Description |
---|---|---|---|
url |
string |
- |
The URL of the resource to load (JavaScript or CSS). |
type |
'script' | 'style' |
- |
Specifies whether the resource is a JavaScript (script ) or a CSS file (style ). |
options |
Partial<HTMLScriptElement> | Partial<HTMLLinkElement> |
{} |
Optional attributes for the <script> or <link> elements, such as async , defer , or id . |
timeout |
number |
10000 |
The time in milliseconds to wait before resolving if the resource fails to load. |
forceReload |
boolean |
false |
If true , forces reloading the resource even if it was already loaded. |
➤ Methods
Method | Parameters | Returns | Description |
---|---|---|---|
loadResource |
{ url, type, options?, timeout?, forceReload? }: ResourceConfig |
Promise<void> |
Dynamically loads a JavaScript or CSS resource based on the configuration object. |
➤ Examples
Load a JavaScript File
injector
.loadResource({
url: 'https://example.com/script.js',
type: 'script',
options: { async: true },
timeout: 5000,
forceReload: true,
})
.then(() => console.log('Script loaded'))
.catch(() => console.error('Failed to load script'));
Load a CSS File
injector
.loadResource({
url: 'https://example.com/styles.css',
type: 'style',
timeout: 7000,
})
.then(() => console.log('Style loaded'))
.catch(() => console.error('Failed to load style'));
Handle Multiple Resources
Promise.all([
injector.loadResource({
url: 'https://example.com/script1.js',
type: 'script',
}),
injector.loadResource({
url: 'https://example.com/style1.css',
type: 'style',
}),
])
.then(() => console.log('All resources loaded'))
.catch(() => console.error('One or more resources failed to load'));
➤ License
resource-injector is released under MIT license