React 中使用 worker 和 decode 優化 image 的加載

圖片加載佔據了一個 web 應用的較多資源。javascript

這篇文章中,咱們實現一個 ImgWorker 組件,知足如下功能:java

  • image 可選擇的 worker 加載,而且作好優雅降級
  • decode 解碼,而且作好優雅降級
  • miniSrc 和 src 競速加載

注意,在性能較低的機器,開啓 worker 進程下載的開銷大於直接使用主進程下載的開銷; 使用 worker 須要主動傳遞 worker 屬性爲 true 開啓react

組件代碼

先上代碼,後續對關鍵代碼作一些解釋:web

src/react-img-worker.js :typescript

import * as React from 'react';

const blobUrl = new Blob(
  [
    ` self.addEventListener('message', event => { const [url, type] = event.data; fetch(url, { method: 'GET', mode: 'no-cors', cache: 'default' }).then(response => { return response.blob(); }).then(_ => postMessage([url, type])).catch(console.error); }) `,
  ],
  { type: 'application/javascript' }
);

interface IImgWorkerProps
  extends React.DetailedHTMLProps<
    React.ImgHTMLAttributes<HTMLImageElement>,
    HTMLImageElement
  > {
  boxProps?: React.DetailedHTMLProps<
    React.ImgHTMLAttributes<HTMLImageElement>,
    HTMLImageElement
  >;
  miniSrc?: string;
  objectFit?: 'fill' | 'contain' | 'cover' | 'none' | 'scale-down';
  renderLoading?: any;
  worker?: boolean;
}

interface IImgWorkerState {
  isLoading: boolean;
  src: string;
}

export class ImgWorker extends React.Component< IImgWorkerProps, IImgWorkerState > {
  public static defaultProps = {
    objectFit: 'cover',
  };

  public div: any = null;
  public image: HTMLImageElement = new Image();
  public isLoadedSrcLock = false;
  public state = {
    isLoading: true,
    src: '',
  };
  public worker: Worker = null as any;
  public constructor(props: IImgWorkerProps) {
    super(props);
    this.image.style.width = '100%';
    this.image.style.height = '100%';
    this.image.style.display = 'none';
    this.image.style.objectFit = this.props.objectFit!;

    // 若是使用 worker 而且瀏覽器支持 worker
    if (this.props.worker && typeof Worker !== 'undefined') {
      this.worker = new Worker(URL.createObjectURL(blobUrl));
      this.worker.addEventListener('message', event => {
        const [url, type] = event.data;

        this.loadImage(url, type);
      });
    }
  }

  public componentDidMount() {
    this.div.appendChild(this.image);
    this.postMessage(this.props);
  }

  public componentWillReceiveProps(nextProps: IImgWorkerProps) {
    if (nextProps.objectFit !== this.props.objectFit) {
      this.image.style.objectFit = nextProps.objectFit!;
    }
    let isPostMessage = false;
    if (nextProps.miniSrc !== this.props.miniSrc) {
      isPostMessage = true;
    }
    if (nextProps.src !== this.props.src) {
      isPostMessage = true;
    }

    // 若是 src 或 miniSrc 更新,從新請求
    if (isPostMessage) {
      this.isLoadedSrcLock = false;
      this.postMessage(nextProps);
    }
  }

  public componentWillUnmount() {
    if (this.image) {
      this.image.onload = null;
      this.image.onerror = null;
    }
    if (this.worker) {
      this.worker.terminate();
    }
  }

  public loadImage = (url: string, type: string) => {
    // 若是 src 已經被設置,攔截後續的更新
    if (this.isLoadedSrcLock) {
      return;
    }
    if (type === 'src') {
      this.isLoadedSrcLock = true;
    }

    this.image.src = url;
    this.image.decoding = 'async';
    this.image.decode !== undefined
      ? this.image
          .decode()
          .then(this.onLoad)
          .catch(this.onLoad)
      : (this.image.onload = this.onLoad);
  };

  public onLoad = () => {
    this.image.style.display = 'block';
    this.setState({
      src: this.image.src,
      isLoading: false,
    });
  };

  public postMessage = (props: IImgWorkerProps) => {
    if (props.miniSrc) {
      if (this.worker) {
        this.worker.postMessage([props.miniSrc, 'miniSrc']);
      } else {
        this.loadImage(props.miniSrc, 'miniSrc');
      }
    }

    if (props.src) {
      if (this.worker) {
        this.worker.postMessage(this.worker.postMessage([props.src, 'src']));
      } else {
        this.loadImage(props.src, 'miniSrc');
      }
    }
  };

  public render() {
    const { boxProps, renderLoading: Loading, src: _src, ...rest } = this.props;
    const { isLoading } = this.state;

    return (
      <div ref={r => (this.div = r)} {...rest}> {Loading && isLoading && ( <Loading key="img-worker-loading" isLoaing={isLoading} /> )} </div> ); } } 複製代碼

代碼是 typescript 編寫的,這是爲了組件發版能夠更簡便的生成.d.ts 文件,內容很簡單,其中關鍵在於兩處:npm

  1. 建立一個 worker
this.worker = new Worker(URL.createObjectURL(blobUrl));
複製代碼
  1. 使用 decode

decode 的功能網上有許多文章,這裏不展開api

const image = new Image();
image.src = url;
image.decoding = 'async';
image.decode !== undefined
  ? image
      .decode()
      .then(this.onLoad)
      .catch(this.onLoad)
  : (image.onload = this.onLoad);
複製代碼

使用

使用默認 image loader, ImgWorker 保留了 <img /> 標籤原有的全部 api瀏覽器

import { ImgWorker } from './react-img-worker';

export default () => {
  return <ImgWorker src="http://example.png" />;
};
複製代碼

使用 worker loader:app

import { ImgWorker } from './react-img-worker';

export default () => {
  return <ImgWorker worker src="http://example.png" />;
};
複製代碼

支持 mini 圖片,若是 設置了 miniSrc 會並行加載 miniSrc 和 src;若 miniSrc 優先加載完,顯示 miniSrc;若 src 優先加載完會攔截這次後續的圖片更新。cors

使用 worker + miniSrc + src:

import { ImgWorker } from './react-img-worker';

export default () => {
  return (
    <ImgWorker
      worker
      miniSrc="http://example.mini.png"
      src="http://example.png"
    />
  );
};
複製代碼

直接使用 react-img-worker 庫

爲了方便使用,以上代碼已發佈至 npm,能夠直接使用

$ yarn add react-img-worker
複製代碼

但願有對君有幫助:)

相關文章
相關標籤/搜索