https://github.com/kermage/lazyscripts
Delay script loading until user interaction or timeout
https://github.com/kermage/lazyscripts
javascript-utility lazy-loading site-optimization
Last synced: 5 days ago
JSON representation
Delay script loading until user interaction or timeout
- Host: GitHub
- URL: https://github.com/kermage/lazyscripts
- Owner: kermage
- License: mit
- Created: 2024-02-19T16:25:27.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2025-04-22T06:36:21.000Z (10 months ago)
- Last Synced: 2025-09-15T18:24:23.786Z (6 months ago)
- Topics: javascript-utility, lazy-loading, site-optimization
- Language: TypeScript
- Homepage:
- Size: 80.1 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# LazyScripts
> "A lightweight JS utility that loads your scripts only after user interaction or after a specified time."
## Usage
Add the main loader `` tag normally to your HTML:
```html
<script src="https://unpkg.com/lazyscripts.js" data-timeout="3500" data-lazyscripts>
```
- `data-timeout="3500"` — (optional) Force load all scripts after 3.5 seconds if no user interaction detected
- `data-lazyscripts` — (optional) Script identifier for integrations like WordPress; [see example below](#wordpress)
Update scripts to use `type="lazyscript"` and specify the URL in `data-src`:
```html
```
Module scripts are supported and can be specified with `data-type="module"`:
```html
```
Inline scripts and the loading strategies `async` & `defer` are supported as well:
```html
console.log("Inline script", "LOADED!");
```
## Example
Check the [`/tests`](/tests) folder for a working implementation.
### WordPress
Automatically convert all scripts to lazy-loaded versions using the [`WP_HTML_Tag_Processor`](https://developer.wordpress.org/reference/classes/wp_html_tag_processor):
```php
add_action(
'template_redirect',
function () {
ob_start(
function ( $buffer ) {
$html = new WP_HTML_Tag_Processor( $buffer );
while ( $html->next_tag( 'script' ) ) {
if ( null !== $html->get_attribute( 'data-lazyscripts' ) ) {
continue; // Skip the main loader
}
$src = $html->get_attribute( 'src' );
$type = $html->get_attribute( 'type' );
if ( $src ) {
$html->set_attribute( 'data-src', $src );
$html->remove_attribute( 'src' );
}
if ( $type && ! in_array( $type, array( 'text/javascript', 'module' ), true ) ) {
// https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script/type
continue;
}
$html->set_attribute( 'data-type', $type );
$html->set_attribute( 'type', 'lazyscript' );
}
return $html->get_updated_html();
}
);
}
);
```