resource-injector
v0.0.1-alpha.3
Published
The ResourceInjector class dynamically loads JavaScript and CSS into the webpage, ensuring each resource is loaded only once, with error handling and optional load timeouts.
Downloads
138
Maintainers
Readme
600B gzipped
➤ Install
$ yarn add resource-injector
➤ Import
import ResourceInjector from 'resource-injector';
➤ Usage
const resourceInjector = new ResourceInjector();
resourceInjector
.loadScript('https://example.com/script.js', { async: true }, 5000)
.then(() => console.log('Script loaded successfully'))
.catch(() => console.error('Failed to load script'));
resourceInjector
.loadStyle('https://example.com/style.css', {}, 5000)
.then(() => console.log('Style loaded successfully'))
.catch(() => console.error('Failed to load style'));
➤ Options
| Option | Type | Default | Description |
|:---------:|:--------------------------------------------------------:|:-------:|:------------------------------------------------------------------------------------------------|
| jsUrl
| string
| -
| The URL of the JavaScript file to load. |
| cssUrl
| string
| -
| The URL of the CSS file to load. |
| 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. |
➤ Methods
| Method | Parameters | Returns | Description |
|:---------------|:-------------------------------------------------------------------------:|:---------------:|:-------------------------------------------------------|
| loadScript()
| (jsUrl: string, options?: Partial<HTMLScriptElement>, timeout?: number)
| Promise<void>
| Dynamically loads a JavaScript file into the document. |
| loadStyle()
| (cssUrl: string, options?: Partial<HTMLLinkElement>, timeout?: number)
| Promise<void>
| Dynamically loads a CSS file into the document. |
➤ Examples
Load a JavaScript File
const resourceInjector = new ResourceInjector();
resourceInjector
.loadScript('https://example.com/script.js', { async: true }, 5000)
.then(() => console.log('Script loaded'))
.catch(() => console.error('Failed to load script'));
Load a CSS File
resourceInjector
.loadStyle('https://example.com/style.css', {}, 5000)
.then(() => console.log('Style loaded'))
.catch(() => console.error('Failed to load style'));
Handle Multiple Resources
Promise.all([
resourceInjector.loadScript('https://example.com/script1.js'),
resourceInjector.loadStyle('https://example.com/style1.css')
])
.then(() => console.log('All resources loaded'))
.catch(() => console.error('One or more resources failed to load'));
➤ License
resource-injector is released under MIT license