https://github.com/3846masa/blurhash-sw
The BlurHash API provided by ServiceWorker.
https://github.com/3846masa/blurhash-sw
blurhash serviceworker
Last synced: about 2 months ago
JSON representation
The BlurHash API provided by ServiceWorker.
- Host: GitHub
- URL: https://github.com/3846masa/blurhash-sw
- Owner: 3846masa
- License: mit
- Created: 2021-10-03T03:55:18.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2025-04-18T15:32:27.000Z (about 2 months ago)
- Last Synced: 2025-04-18T18:39:42.395Z (about 2 months ago)
- Topics: blurhash, serviceworker
- Language: TypeScript
- Homepage: https://3846masa.github.io/blurhash-sw/
- Size: 1.88 MB
- Stars: 11
- Watchers: 2
- Forks: 0
- Open Issues: 11
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# BlurHash SW
[](https://www.npmjs.com/package/blurhash-sw)
[](https://unpkg.com/[email protected]/dist/index.js)
[](https://3846masa.mit-license.org)
[](https://github.com/RichardLitt/standard-readme)The BlurHash API provided by ServiceWorker.
[https://github.com/3846masa/blurhash-sw](https://github.com/3846masa/blurhash-sw)
## Table of Contents
- [Install](#install)
- [Usage](#usage)
- [Contributing](#contributing)
- [License](#license)## Install
Add the following code to your ServiceWorker script.
```js
// sw.js
importScripts('https://unpkg.com/[email protected]/dist/index.js');blurhashSW({
routeUrl: '/.blurhash/:blurhash',
width: 32,
height: 32,
});
``````html
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}```
## Usage
See also [demo page](https://3846masa.github.io/blurhash-sw/).
### The easiest way
Set the BlurHash URL as `background-image`.
You should encode the BlurHash hash contained in the URL.
```html
![]()
```### With fade-in transition
Wrap the img element in the div element.
The BlurHash URL should be assigned as `background-image` of the div element.
```html
![]()
```### Using `data-blurhash` attribute
The BlurHash URL is not available until the ServiceWorker is ready.
Therefore, when visiting the site for the first time, `background-image` cannot be loaded.
As a workaround, generate `background-image` based on `data-blurhash` when the ServiceWorker is ready.
```js
navigator.serviceWorker
.register('/sw.js')
.then(() => navigator.serviceWorker.ready)
.then(() => {
const $elemList = document.querySelectorAll('[data-blurhash]');
for (const $elem of $elemList) {
const blurhash = $elem.dataset.blurhash;
$elem.style.backgroundSize = `100% 100%`;
$elem.style.backgroundImage = `url(/.blurhash/${encodeURIComponent(blurhash)})`;
}
});
``````html
![]()
``````html
![]()
```## Contributing
PRs accepted.
## License
[MIT (c) 3846masa](https://3846masa.mit-license.org)