1.4.0 • Published 3 months ago
resource-injector v1.4.0
0.7kB 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
1.4.0
3 months ago
1.3.1
4 months ago
1.3.1-dev.0
4 months ago
1.3.0
4 months ago
1.2.0
4 months ago
1.1.0
5 months ago
1.0.0
7 months ago
0.0.1-alpha.3
7 months ago
0.0.1-alpha.2
7 months ago
0.0.1-alpha.1
7 months ago