Alpine.js directive to lazy load css and js assets
npm install alpine-lazy-load-assetsNote: This package is specifically designed for lazy loading css/js assets but does _not_ handle lazy loading of Alpine components. You should use Async Alpine for that.
However, it is the perfect companion to use alongside Async Alpine to lazy load all the assets required by your Alpine.js components.
- Lazily load CSS and JS files on-demand.
- Prevent redundant loading of the same asset.
- Saves loaded assets in Alpine global state to avoid reloading them, and to check asset existence.
- Position scripts in head, body-start or body-end.
- Optionally dispatch window events when assets have finished loading.
html
src="https://unpkg.com/alpine-lazy-load-assets@latest/dist/alpine-lazy-load-assets.cdn.js"
defer
>
`
NPM
`bash
npm install alpine-lazy-load-assets -D
`#### Script Bundle
To add the
x-load-css and x-load-js directives to your project, register the plugin with Alpine.js.
`js
import Alpine from 'alpinejs';
import AlpineLazyLoadAssets from 'alpine-lazy-load-assets';Alpine.plugin(AlpineLazyLoadAssets);
window.Alpine = Alpine;
window.Alpine.start();
`#### Script include
`js
import AlpineLazyLoadAssets from 'alpine-lazy-load-assets'document.addEventListener('alpine:init', () => {
window.Alpine.plugin(AlpineLazyLoadAssets)
})
`#### Livewire v3
`js
import { Livewire, Alpine } from '../../vendor/livewire/livewire/dist/livewire.esm';
import AlpineLazyLoadAssets from 'alpine-lazy-load-assets';Alpine.plugin(AlpineLazyLoadAssets);
Livewire.start();
`
Usage
$3
* The x-load-js directive adds a