Development history of Icon
Img’s initial plan
When we were kids, we used to apply an icon to the front end like this:
- Find related picture resources online or provided by visual students
- Download the assets/img folder and rename it to index.png
- Use on the page
<img src="assets/img/index.png" />
Or simply reference a remote image address - Use CSS to control the style of the IMG tag
Before I grew up, some people said, boy, you can’t do this. If there are many ICONS on the page, the request will be an image request. Listen to the adult said, at the beginning of their own scared to grasp baidu once. One article, Best Practices for Speeding Up Your Web Site, is now known as the Yahoo Front End Performance Optimization Guidelines. The first:
Take care to Minimize HTTP Requests.
Obviously, because of the display of Icon, there are so many HTTP requests in the page, which is a little unreasonable. Your excellency is quite right.
As a result, I opened Baidu again. How can I use icon elegantly? CSS Sprite, what is it?
CSS Sprites are a means of combining multiple images into a single image file for use on a website, To help with performance CSS Sprites are a way of combining multiple images into one image in a website for optimal performance.
With CSS Sprite, the front end only requests images once when used, and controls the display icon through background-IMG and background-position properties of CSS. Obviously, the number of HTTP requests has been reduced and the fun is finally back.
However, not happy how long, the egg pain thing came. Other functions in the project need to add additional icon, the UI can only be re-made, if it does not affect the previous icon position is ok, if the previous icon position is adjusted, the CSS written before has to be changed.
If the UI had to be tweaked every time such a change was made, the UI would probably go crazy. Fortunately, tools quickly emerged in the community to automate these tasks. Sprity is a tool that automatically synthesizes Sprite diagrams according to their configuration. At the time, it also provided a Gulp/Grant based plugin. It’s clear that this technology isn’t very useful at the moment, and the last project submitted on Sprity Github was two years ago. CSS Sprites: What They Are, Why They’re Cool, and How To Use Them showed you How To Use tools To automatically generate Sprite images back then.
To optimize performance, there was also a technology called Data URIs that could encode images and inline them in stylesheets, avoiding additional HTTP requests and eliminating the need to configure background-positions. There may also be performance issues with this technique introduced to optimize performance, as described in this article, Data URIs.
Icon Font
The development of Web Font benefits from the @font-face attribute of CSS3.
Allows web developers to specify online fonts for their web pages. By doing so, @font-face eliminates the need to rely on a user’s computer font.
The idea of Icon Font comes from Web Font, which uses the way fonts are designed for ICONS. Among them, Alibaba’s open source icon library IconFont is widely used. The Iconfont icon library is used as an example to describe how to use it.
After logging in to IconFont, you can search for the icon you want and add it to the shopping cart. The ICONS in the shopping cart can be added to the project. Iconfont provides the ability to manage ICONS by project. There are three ways to use web ICONS in the project: Unicode, Font Class, and Symbol.
Unicode reference
Unicode is the original use of fonts on the web. It has the following features:
- Best compatibility, support ie6+, and all modern browsers.
- Support to dynamically adjust icon size, color and so on according to the font.
- But because it is a font, it does not support multicolor. Use only monochrome ICONS on the platform, even if there are multi-colored ICONS in the project, the color will be automatically removed.
Use steps:
Step 1: Copy the font-face generated under the project
@font-face {font-family: 'iconfont'; src: url('iconfont.eot'); src: url('iconfont.eot? #iefix') format('embedded-opentype'), url('iconfont.woff') format('woff'), url('iconfont.ttf') format('truetype'), url('iconfont.svg#iconfont') format('svg'); }Copy the code
Step 2: Define styles that use iconFONT
.iconfont{ font-family:"iconfont" ! important; font-size:16px; font-style:normal; -webkit-font-smoothing: antialiased; - its - text - stroke - width: 0.2 px; -moz-osx-font-smoothing: grayscale; }Copy the code
Step 3: Pick the appropriate icon and get the font code to apply to the page
<i class="iconfont">3</i>
Copy the code
The font – class reference
Font -class is a variant of Unicode, mainly to solve the problem of unicode writing is not intuitive, ambiguous semantics.
Compared to unicode usage, it has the following features:
- Good compatibility, support ie8+, and all modern browsers.
- It is more intuitive to write than Unicode. It’s easy to tell what the icon is.
- Because you use class to define ICONS, you only need to change the Unicode reference in the class to replace the icon.
- Multicolor ICONS are not supported, however, because they are essentially fonts.
The steps are as follows:
Step 1: Copy the FontClass code generated under the project:
//at.alicdn.com/t/font_8d5l8fzk5b87iudi.css
Copy the code
Step 2: Pick the appropriate icon and get the class name to apply to the page
<i class="iconfont icon-xxx"></i>
Copy the code
The symbol referenced
This is a completely new way of using it, and it’s the mainstream of the future, and it’s what the platform currently recommends. This usage actually makes a collection of SVG, which has the following characteristics compared to the above two:
- Support for multi-color ICONS, no longer limited by monochrome.
- With a few tricks, it is possible to adjust styles like fonts by font size and color.
- Poor compatibility, support for IE9 +, and modern browsers.
- Browsers render SVG with mediocre performance, not as good as PNG.
The steps are as follows:
Step 1: Copy the symbol code generated under the project:
//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js
Copy the code
Step 2: Add generic CSS code (just once) :
<style type="text/css"> .icon { width: 1em; height: 1em; Vertical - align: 0.15 em. fill: currentColor; overflow: hidden; } </style>Copy the code
Step 3: Select the corresponding icon and get the class name, apply to the page:
<svg class="icon" aria-hidden="true">
<use xlink:href="#icon-xxx"></use>
</svg>
Copy the code
Svg Icon
Because of IconFont’s shortcomings in displaying ICONS, developers began to use SVG as an alternative to displaying ICONS.
The article Inline SVG vs Icon Fonts details the differences between Inline SVG and Icon Fonts.
The main disadvantages of Iconfont:
-
Browsers treat it as text for anti-aliasing optimization, and text rendering may be different in different systems
-
When an Icon is displayed as a font, its spacing and spacing are affected by CSS attributes such as font-size,line-height, word-spacing, etc. The CSS style of its container also affects the spacing of the font Icon.
-
Iconfont supports only monochrome and does not work well in high resolutions.
Here are several ways to use SVG in a project, each with its own advantages and disadvantages:
Img/object labels
An early way to use SVG. The downside is that each icon needs to be saved as an SVG file, which is requested separately when used. Too many ICONS in a project can result in too many HTTP requests.
Inline svg
As the name suggests, writing SVG directly into HTML is a simple and violent way to reduce HTTP requests.
Advantages: You can directly use class to customize SVG styles, which is highly controllable
Disadvantages: poor reusability, low efficiency
Data URIs
CSS directly uses Base64 encoded SVG
.icon{ background: url(data:text/svg+xml; base64,<base64 encoded data>) }Copy the code
Advantages: No additional references to SVG files are required
Disadvantages: Poor control, no CSS for style customization, potential efficiency issues
svg sprite
The most basic SVG Sprite technology is similar to CSS Sprite in that it controls the position of the display through properties such as background-position. Similar to CSS Sprites, there are tools in the community and online sites that provide methods for generating SVG Sprites.
Advantages: Reduces HTTP requests and can fallback to CSS Sprite
Disadvantages: Poor controllability, cannot easily control styles through CSS
SVG Sprite based on SVG Symbols
SVG Symbols is a way to define SVG references. The SVG Sprite based on this method is an improvement on the traditional SVG Sprite, which improves the call method of obtaining a single Icon in the Sprite. Calls based on SVG Symbols are based on references.
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;" > <symbol id="circle-cross" viewBox="0 0 32 32"> <title>circle-cross icon</title> <path d="M16 1.333q2.99 0 5.703 1.161t4.677 3.125 3.125 4.677 1.161 5.703-1.161 5.703-3.125 4.677-4.677 3.125-5.703 1.161-5.703-1.161-4.677-3.125-3.125-4.677-1.167-5.703 1.161-5.703 3.125-4.677-3.125 5.703-1.163-1.161-5.703 zm0 2.667q-2.438 0-4.661.953 T-3.828 2.557-2.557 3.828-.953 4.661.953 4.661 2.557 3.8661.953 3.828-2.557 4.661.953 4.661-.953 3.828-2.557 2.557 3.828.953-4.661-953-4.661-2.557-3.828-3.828-2.557-4.661 -. 953 zm3. 771 6.885 q., 552 .948.391 T.396.943 -.396.948 L-2.833 2.833 2.833 2.823q.396.396.396.938 0 . 552-396.943 t - 948.391-938-385-2.833-2.823-2.823-2.823 l q -.. 385.385-948.385-552 0. 943-385 t - 391-938 q0-563.385-948 l2. 833-2.823-2.833-2.833 q - 385 -, 385-385-938. 391-948.943 - t. 396.948.396 l2.823 2.833 2.833-2.833q.396-.396.938-.396z"/> </symbol> <symbol id="circle-check" viewBox="0 0 32 32"> <title>circle-check Icon </title> <path D ="M16 1.33q2.99 0 5.703 1.161t4.677 3.125 3.125 4.677 1.161 5.703-1.161 5.703-3.125 4.677-4.677 3.125-5.703 1.161-5.703-1.161-4.677-3.125-3.125-4.677-1.167-5.703 1.161-5.703 3.125-4.677 4.677-3.125 5.703-1.161-zm0 2.667q-2.438 0-4.661.953 T-3.828 2.557-2.557 3.828-.953 4.661.953 4.661.953 4.661 2.557 3.828 3.828 2.557 4.661.953 4.661-.953 3.828-2.557-2.557-3.828.953-4.661-953-4.661-2.557-3.828-3.828-2.557-4.661 -. 953 zm4. 49 7.99 q., 552 . 943.391 t. 391.943. 396.948 l - 5.656. 5.656 q - 385.385-938.385-563 0. 948-385-2.833-2.823 l q -, 385 -, 385 -, 385 -. 948 0-552.391 -. 943 t. 943 -, 391.948.396 l1.885 1.885 4.708 4.719 q. 396-396.948 -. 396 z "/ > < / symbol > <! -... --> </svg>Copy the code
Each Symbol sets an ID as its referenced name.
Usage:
Step 1: Insert the above SVG as the first child of the body.
Step 2: Use SVG by using xlink:href where icon references are required
<svg class="icon">
<use xlink:href="#circle-cross"></use>
</svg>
Copy the code
The above method of making SVG-sprite based on Symbol is convenient to use. By using ID to reference the corresponding SVG, it avoids using background-position to reference SVG. Even if a new SVG-Sprite needs to be merged later, as long as the symbol ID of the corresponding SVG does not change before and after the merge, the SVG already used in the business before and after the merge does not need to be changed.
Webpack integration SVG – Sprite
Vue-svg-icon in the demo details the steps to integrate the SVG-Icon solution in a Webpack-based VUE single-page project.
Step 1: Make svG-Sprite:
Add svG-sprite-loader to webpack and add the following configuration:
{
test: /\.svg$/,
include: [resolve('src/components/svg-icon/icons')],
use: [
{
loader: 'svg-sprite-loader',
options: {
symbolId: 'icon-[name]'
}
}
]
},
Copy the code
Svg-sprite-loader makes an SVG Sprite from the specified folder we reference and inserts it into the body of the HTML.
It should be noted that we should specify a folder to store all SVG ICONS in our project. Vue-cli also provides urL-loader to process SVG, so we should add the following configuration to avoid SVG files under icon being processed by URL-loader.
{ test: /\.(png|jpe? g|gif|svg)(\? . *)? $/, loader: 'url-loader', exclude: [resolve(' SRC /components/ svG-icon/ICONS ')], // Default: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } },Copy the code
You can exclude SVG files in the icon folder from being processed by urL-loader.
Step 2: Encapsulate the SVG Component as it is used
The above shows how to use SVG with use after generating an SVG Sprite. Encapsulate the svgicon.vue component for easy reference in the project.
<! -- SvG-icon component, < SVG :class="svgClass" aria-hidden="true"> <use :xlink:href="iconName"></use> </ SVG > </template> <script> // Import all SVG files const requireAll = requireContext => requireContext.keys().map(requireContext); const req = require.context('./icons', false, /\.svg$/); requireAll(req); export default { name: 'svg-icon', props: { iconClass: { type: String, required: true, }, className: { type: String, }, }, computed: { iconName() { return `#icon-${this.iconClass}`; }, svgClass() { if (this.className) { return `svg-icon ${this.className}`; } return 'svg-icon'; ,}}}; </script> <style scoped> .svg-icon { width: 40px; height: 40px; Vertical - align: 0.15 em. fill: currentColor; overflow: hidden; } </style>Copy the code
Possible problems with using SVG Sprite
Problems with SVG file simplification
Why do YOU want to simplify SVG files?
SVG files exported by UI’s tools usually contain a lot of redundant and useless information, such as editor metadata, comments, hidden elements, default values and other content that can be deleted without affecting normal SVG rendering.
Iconmoon. IO and Iconfont provide online SVG simplification.
In large and medium projects with multiple collaborators and frequent changes to SVG files, it is clear that this reliance on manual processes to streamline SVG is no longer sufficient for rapid development. So we need to integrate similar tools to streamline SVG into our workflows.
Svgo (SVG Optimizer) is an SVG file optimization tool based on Nodejs. It can realize the requirements of customized and simplified SVG through a series of configuration items.
Svgo-loader A webPack – and SvGo – based loader for SVG optimization.
Usage:
webpack.base.conf.js
// Import svgo configuration file const svgoConfig = require('.. /config/svgo-config.json'); . { test: /\.svg$/, include: [resolve('src/components/svg-icon/icons')], use: [ { loader: 'svg-sprite-loader', options: { symbolId: 'icon-[name]' } }, { loader: 'svgo-loader', options: svgoConfig, } ] },Copy the code
Svgo-config. json(defines rules for simplifying SVG)
{ "plugins": [ { "cleanupAttrs": true }, { "cleanupEnableBackground": true }, { "cleanupIDs": true }, { "cleanupListOfValues": true }, { "cleanupNumericValues": true }, { "collapseGroups": true }, { "convertColors": true }, { "convertPathData": true }, { "convertShapeToPath": true }, { "convertStyleToAttrs": true }, { "convertTransform": true }, { "mergePaths": true }, { "removeComments": true }, { "removeDesc": true }, { "removeDimensions": true }, { "removeDoctype": true }, { "removeEditorsNSData": true }, { "removeEmptyAttrs": true }, { "removeEmptyContainers": true }, { "removeEmptyText": true }, { "removeHiddenElems": true }, { "removeMetadata": true }, { "removeNonInheritableGroupAttrs": true }, { "removeRasterImages": true }, { "removeTitle": true }, { "removeUnknownsAndDefaults": true }, { "removeUselessDefs": true }, { "removeUnusedNS": true }, { "removeUselessStrokeAndFill": True}, {"removeAttrs": {"attrs": "fill"}, {" removeMLProcinst ": true}, {"removeStyleElement": true }, { "removeUnknownsAndDefaults": true}, { "sortAttrs": true } ] }Copy the code
State – dependent SVG-Icon and thoughts on polychromatic problems
In the course of Web development, we often come across state-related ICONS. For example, when the user clicks or hover, we need to change the color of the icon accordingly. With the Iconfont scheme, because of the nature of the font, we can directly control the color of the font using CSS.
The SVG color used in the SVG-Icon scheme is a fill color mechanism. The specific path is colored with the fill attribute. If the associated path does not specify a fill attribute, it inherits the parent element’s color attribute to fill.
Therefore, state color changes in SVG-ICON scheme can be divided into the following two situations:
- The state change of multi-color SVG-icons is not the color change of a single path. When the state changes, the ICONS in different states are directly replaced
- The state change of multi-color SVG-icon only involves the color change under a single path. At this time, the fill attribute of this path can be left blank, and the color attribute of its parent element can be modified through CSS to achieve the purpose of changing the color of icon.
conclusion
The SVG-Icon scheme based on SVG-Sprite has been around since 2014, but was not widely adopted due to browser compatibility and other reasons. Today, with newer technologies, compatibility is clearly no longer a barrier for svG-Icon applications. Mobile android 3.x, IE 9+ can adopt THE ICON scheme of SVG-Icon. Through investigation, it is found that svG-Icon technology has been applied to the following solutions:
- Github has adopted SVG as its icon presentation, inline SVG
- The iconfont host uses inine SVG to display all its ICONS
- Jingdong adopts SVG Sprite scheme based on SVG Symbol to display ICONS in some ICONS (phone charges, air tickets, etc.)
- Tencent video part icon (pause, play) adopts SVG Sprite scheme based on SVG Symbol
Any discussion of technical solutions cannot be separated from their application scenarios. In the actual development, due to various reasons, there may be multiple ICON schemes in parallel, so the actual development process should be analyzed on a case-by-case basis.
Reference links:
- Hand to hand, with your elegant use of icon
- ICONS on the Web
- Future will be hot: SVG Sprite technology introduction
- CSS Sprites: What They Are, Why They’re Cool, and How To Use Them
- Data URIs
- Embracing the New Trend in Web Design: SVG Sprites for practical applications
- Inline SVG vs Icon Fonts
- New trend in Web design: SVG instead of Web Icon Font
- HOW TO CREATE AND MANAGE SVG SPRITES
- Webpack SVG plugin – Sprite – loader
- Use SVG Sprite instead of iconFont
- SVG
symbol
a Good Choice for Icons - Introduction to and initial experience with SVGo, the SVG compact compression tool