event-import-then-function
html
<input
onchange="import('/js/form.js').then(M => M.default(this))"
/>
<input
onchange="import('/js/form.js').then(M => M.reverse(this))"
/>
<input
onchange="import('/js/form.js').then(M => M.upperCase(this))"
/>
note: the M is just short for Module
form.js
console.log('form.js loaded')
export const reverse = element => {
element.value = [...element.value].reverse().join("");
}
export const upperCase = element => {
element.value = element.value.toUpperCase();
}
export default element => {
console.log(element.value)
}
In the above example form.js
will be loaded only once, no matter how many times the onchange events are triggered. So you'll only ever see one "form.js loaded" in the console.
Since the loading of form.js is deferred until after the onchange event has been triggered, there will be a slight delay whilst the browser fetches it.
If you want to avoid this delay you can always prefetch the resource by adding:
<link rel="prefetch" href="/js/form.js" />
to the html. This will of course fetch the file regardless if the user ever needs it.
Top comments (0)