Skip to content

Instantly share code, notes, and snippets.

@neutraltone
Last active January 25, 2018 03:22
Show Gist options
  • Save neutraltone/fbd9e7bf5d64fc13b10c to your computer and use it in GitHub Desktop.
Save neutraltone/fbd9e7bf5d64fc13b10c to your computer and use it in GitHub Desktop.
A gulp task for creating SVG sprites, loading them into your template with AJAX and styling them with CSS
/**
* Gulp Packages
* =============
* Import our gulp packages.
*/
import gulp from 'gulp';
import svgmin from 'gulp-svgmin';
import svgstore from 'gulp-svgstore';
import cheerio from 'gulp-cheerio';
/**
* Constants
* ---------
* Constants used throughout this boilerplate.
*/
const pkg = require('./package.json');
/**
* Directory Templates
* -------------------
* Here we setup the various project directories
* making it easy to amend at a later date.
*/
const project = {
src: 'src',
dist: 'dist'
};
const iconPath = {
src: `${project.src}/icons/{,*/}*.svg`,
dest: `${project.dist}/assets/img`
}
/**
* SVG Sprite
* ----------
* - Define prefix based on folder name
* - Sprite svg's
* - Copy sprite.svg to destination
*/
gulp.task('svg-sprite', () => {
return gulp.src(spritePath.src)
.pipe(svgmin())
.pipe(svgstore())
.pipe(cheerio($ => $('svg').attr('style', 'display:none')))
.pipe(gulp.dest(spritePath.dest))
});
.icon {
width: 1em;
height: 1em;
fill: currentColor;
&--facebook {
fill: #3b5998;
&:hover {
fill: #59983b;
}
}
}
<!doctype html>
<html lang="en">
<head>
<script>
// Ajax SVG sprite.
window.addEventListener('load', function (event) {
var ajax = new XMLHttpRequest();
ajax.open('GET', '/assets/img/sprite.svg', true);
ajax.send();
ajax.onload = function (e) {
var div = document.createElement('div');
div.innerHTML = ajax.responseText;
document.body.insertBefore(div, document.body.childNodes[0]);
}
});
</script>
</head>
<body>
<svg class="icon icon--facebook">
<use xlink:href="#icon-facebook" />
</svg>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment