Import remote resource(js or css) asynchronously.
To avoid duplicating runtime-import package, loading a umd bundle file in html is recommended.
The newest umd bundle file is:
https://unpkg.com/runtime-import@3.0.0/dist/runtime-import.umd.js
npm i runtime-import --save
Import a javascript file, if the file is in UMD format, return it's export object.
import { importScript } from 'runtime-import'
try {
const $ = await importScript('//foobar.com/jquery.js')
} catch (err) {
console.error(err)
}
Import a css file.
import { importStyle } from 'runtime-import'
try {
await importStyle('//foobar.com/bootstrap.css')
} catch (err) {
console.error(err)
}
Import a component. In umd mode, if the entry javascript file is UMD, return it's export object.
Options:
interface ImportComponentOptions {
// JavaScript options.
scripts: {
// Dependent file URLs.
dependencies?: string[]
// UMD entry file URL.
entry: string
// Is the entry file a UMD file? The default value is `true`.
umd?: boolean
// Value of the `crossOrigin` attribute of the <script> element, the default value is "anonymous".
crossOrigin?: string
}
// Stylesheet options.
styles?: {
// CSS URL list.
urls: string[]
}
}
Note:
- The default value of the
crossOrigin
field inimportComponent
's options istrue
. This sets thecrossorigin
attribute of the<script>
elements created byimportComponent
to"anonymous"
. If you do not want thecrossorigin
attribute to be set, ensure that thecrossOrigin
field inimportComponent
's options is set to""
.
Example:
import { importComponent } from 'runtime-import'
try {
const bootstrap = await importComponent({
scripts: {
dependencies: []
entry: '//foobar.com/bootstrap.js',
},
styles{
urls: ['//foobar.com/bootstrap.css'],
}
})
} catch (err) {
console.error(err)
}