LoginSignup
5
2

More than 1 year has passed since last update.

CSSスプライトを使って画像読込を効率化したい

Posted at

この記事は ミライトデザイン Advent Calendar 2021 16日目の記事です。

やりたいこと

Webページ上でアイコンのような小さな画像ファイルをたくさんロードするのは通信が非効率になりがち。
これらのファイルを1つのファイルにまとめて出力したい!
ということでCSSスプライト&結合済画像ファイルを自動で生成しよう。

今回はnpmモジュールの spritesmith-cli を使って変換している。

準備

変換用JSコード

spritesmith-cli を使って変換するためのコード。
ファイルは必ず .spritesmith.js という名前で保存しよう。

.spritesmith.js
'use strict';

const util = require('util');

module.exports = {
  cssTemplate: '.spritesmith.css.handlebars',
  destImage: 'images/hoge.png',
  destCSS: 'css/_hoge.scss',
  imgPath: '/images/hoge.png',
  padding: 2,
  src: 'data/hoge/*.png'
};
  • cssTemplate: テンプレートファイル(後述)のファイルパス
  • destImage: スプライト画像の出力先ファイルパス
  • destCSS: スプライト画像を利用するためのCSSの出力先ファイルパス
  • imgPath: スプライト画像をWeb上から読み出すためのパス
  • padding: 画像ごとのパディング(少しとっておくと隣の画像が表示される事故が起きない)
  • src: 元画像ファイルのパス

変換用CSSテンプレート

以下.scssを出力するためのサンプル。
今回Retina対策として画像は倍サイズのものを用意して1/2で表示している。

.spritesmith.css.handlebars
.icon {
{{#items}}
  &.icon-{{name}} {
    &:before {
      content: "";
      background-image: url({{{escaped_image}}});
      background-position: ({{px.offset_x}} / 2) ({{px.offset_y}} / 2);
      background-repeat: no-repeat;
      background-size: ({{px.total_width}} / 2) ({{px.total_height}} / 2);
      width: ({{px.width}} / 2);
      height: ({{px.height}} / 2);
    }
  }
{{/items}}
}

変換方法

以下コマンドを実行すると.scss/.pngファイルが自動生成される。
適当に組み込んでビルドして使おう。

npx spritesmith-cli

使い方

以下のようにHTMLを記述することで画像を表示できる。

index.html
<i class="icon icon-xxx"></i>
5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2