1.4.0 • Published 3 months ago

resource-injector v1.4.0

Weekly downloads
-
License
MIT
Repository
github
Last release
3 months ago

npm GitHub package version NPM Downloads

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

OptionTypeDefaultDescription
urlstring-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).
optionsPartial<HTMLScriptElement> \| Partial<HTMLLinkElement>{}Optional attributes for the <script> or <link> elements, such as async, defer, or id.
timeoutnumber10000The time in milliseconds to wait before resolving if the resource fails to load.
forceReloadbooleanfalseIf true, forces reloading the resource even if it was already loaded.

Methods

MethodParametersReturnsDescription
loadResource{ url, type, options?, timeout?, forceReload? }: ResourceConfigPromise<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