Skip to content

Instantly share code, notes, and snippets.

@jonlong
Created December 17, 2014 16:45
Show Gist options
  • Save jonlong/239c2a55bb58f9859f7b to your computer and use it in GitHub Desktop.
Save jonlong/239c2a55bb58f9859f7b to your computer and use it in GitHub Desktop.
SVG Sprite approach

Gulp Task

  • Copies individual SVGs to assets folder (in case you need to reference them in CSS)
  • Creates a sprite sheet called icons.svg and gives each sprite an ID based on its filename.
  • Cuts all individual SVGs into fallback PNGs, which are auto-loaded in IE by svg4everybody.

HTML

  • conditionally loads svg4everybody for IE, and uses svg sprite notation to use a spritesheet of SVG images.
var gulp = require('gulp');
var sprite = require('gulp-svg-sprites');
var raster = require('gulp-raster');
var rename = require('gulp-rename');
var svgo = require('gulp-svgo');
var filter = require('gulp-filter');
var flatten = require('gulp-flatten');
var debug = require('gulp-debug');
var merge = require('merge-stream');
var config = require('../../config/app');
var path = require('path');
/**
* This path gets written into the generated CSS, and
* needs to be relative to the final, built file.
*/
var svgFileName = 'icons';
/*
Minifies and combines SVG files into a sprite sheet, creates
PNG fallbacks, and generates sprite CSS.
*/
gulp.task('svg', function(callback) {
var svg = gulp.src(config.paths.src.images + '/**/*.svg')
.pipe(svgo())
.pipe(gulp.dest(config.paths.build.images + '/svg'))
.pipe(sprite({
preview: false,
mode: 'symbols',
svg: {
symbols: config.paths.build.images + '/' + svgFileName + '.svg'
}
}))
.pipe(gulp.dest(process.cwd()));
var png = gulp.src(config.paths.src.images + '/**/*.svg')
.pipe(raster())
.pipe(rename(function(path) {
path.basename = svgFileName + '.svg.' + path.basename;
path.extname = '.png';
}))
.pipe(flatten())
.pipe(gulp.dest(config.paths.build.images));
return merge(svg, png);
});
<!DOCTYPE html>
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]><html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]><html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SVG Sprite Test</title>
<!--[if lte IE 8]><!-->
<script type="text/javascript" src="/assets/js/polyfills/svg4everybody.ie8.min.js"></script>
<!--<![endif]-->
<!--[if gt IE 8]><!-->
<script type="text/javascript" src="/assets/js/polyfills/svg4everybody.min.js"></script>
<!--<![endif]-->
</head>
<body>
<header class="page-head row">
<svg role="img">
<use xlink:href="/assets/images/icons.svg#logo"></use>
</svg>
</header>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment