An open API service indexing awesome lists of open source software.

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.

Awesome Lists containing this project

README

        

# BlurHash SW

BlurHash SW

[![npm](https://flat.badgen.net/npm/v/blurhash-sw)](https://www.npmjs.com/package/blurhash-sw)
[![filesize](https://flat.badgen.net/badgesize/gzip/file-url/unpkg.com/[email protected]/dist/index.js)](https://unpkg.com/[email protected]/dist/index.js)
[![license](https://flat.badgen.net/badge/license/MIT/blue)](https://3846masa.mit-license.org)
[![standard-readme compliant](https://flat.badgen.net/badge/readme%20style/standard/green)](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
Shibuya 109
```

### 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


Tokyo tower

```

### 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
Kinkaku-ji
```

```html


Himeji castle

```

## Contributing

PRs accepted.

## License

[MIT (c) 3846masa](https://3846masa.mit-license.org)