Skip to content

Commit

Permalink
implement webp-machine detectWebpImage
Browse files Browse the repository at this point in the history
 - webp-machine now optionally takes a "detectWebpImage" function.
 - the default function looks for image filenames ending with ".webp".
 - the regex was updated
 - close #22
  • Loading branch information
chase-moskal committed May 31, 2019
1 parent f5d8609 commit ccc9d7f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
3 changes: 3 additions & 0 deletions source/interfaces.ts
@@ -1,9 +1,12 @@

import {Webp} from "../libwebp/dist/webp.js"

export type DetectWebpImage = (image: HTMLImageElement) => boolean

export interface WebpMachineOptions {
webp?: Webp
webpSupport?: Promise<boolean>
detectWebpImage?: DetectWebpImage
}

export interface PolyfillDocumentOptions {
Expand Down
12 changes: 9 additions & 3 deletions source/webp-machine.ts
Expand Up @@ -2,12 +2,15 @@
import {Webp} from "../libwebp/dist/webp.js"
import {loadBinaryData} from "./load-binary-data.js"
import {detectWebpSupport} from "./detect-webp-support.js"
import {WebpMachineOptions, PolyfillDocumentOptions} from "./interfaces.js"
import {WebpMachineOptions, PolyfillDocumentOptions, DetectWebpImage} from "./interfaces.js"

const relax = () => new Promise(resolve => requestAnimationFrame(resolve))

export class WebpMachineError extends Error {}

export const defaultDetectWebpImage: DetectWebpImage = (image: HTMLImageElement) =>
/\.webp.*$/i.test(image.src)

/**
* Webp Machine
* - decode and polyfill webp images
Expand All @@ -16,15 +19,18 @@ export class WebpMachineError extends Error {}
export class WebpMachine {
private readonly webp: Webp
private readonly webpSupport: Promise<boolean>
private readonly detectWebpImage: DetectWebpImage
private busy = false
private cache: {[key: string]: string} = {}

constructor({
webp = new Webp(),
webpSupport = detectWebpSupport()
webpSupport = detectWebpSupport(),
detectWebpImage = defaultDetectWebpImage
}: WebpMachineOptions = {}) {
this.webp = webp
this.webpSupport = webpSupport
this.detectWebpImage = detectWebpImage
}

/**
Expand Down Expand Up @@ -56,7 +62,7 @@ export class WebpMachine {
async polyfillImage(image: HTMLImageElement): Promise<void> {
if (await this.webpSupport) return
const {src} = image
if (/.*webp.*/i.test(src)) {
if (this.detectWebpImage(image)) {
if (this.cache[src]) {
image.src = this.cache[src]
return
Expand Down

0 comments on commit ccc9d7f

Please sign in to comment.