Optimizing SVG for the Web

From the Author: Webpack is a JavaScript module bundler that transforms web resources such as HTML, CSS, JavaScript, and SVG files and bundles them into a smaller group of files.  Webpack also helps with chunking (splitting into smaller chunks) and managing code dependencies to ensure that the code that needs to be loaded first does this.  How webpack works In this article, we'll go over some of the new features to look out for in webpack in 2021, but first we'll look at what's new in webpack in 2020.  webpack V4 - V5: Important Changes In October 2020, a newer version of webpack was released: webpack 5. This version removes all deprecated elements in V4 and fixes critical bugs to bring the webpack architecture up to par for future improvements.  JavaScript.  Quick Start Learn the basics of JavaScript with a hands-on example of building a web application Learn more Other interesting features in version 5: Long-Term Caching Support - New algorithms to support long-term caching are enabled by default in production mode.  The real hash of the content - previously only the hash of the internal structure was used in webpack.  Webpack 5 will use the real hash of the file content when used [contenthash], which will have a positive effect on long-term caching when only small changes are made to the file.  Modular structure - webpack 5 came with a new feature that allows multiple webpack builds to work together.  See here for the complete changelog.  While 2020 has been a big year for webpack, there is still a lot more to come, which we'll talk about in the following sections.  Please note that these updates are subject to change based on the ever-changing world of web developers.  Webpack roadmap 2021 Improved ESM support Since the ECMAScript Module (ESM) was introduced in 2015, it has become the standard mechanism for code reuse in highly fragmented JavaScript applications.  To improve ESM support, the webpack team is planning to make some important updates.  Self-executing snippets One of the most interesting features of webpack is code splitting.  This feature allows you to split your code into multiple packages that you can download on demand or in parallel.  At the moment, dynamically loaded fragments in webpack usually serve as a container for modules and never execute module code directly.  For example, writing: JavaScript import ("./ module") 1 import ("./ module") Will compile like this: JavaScript __webpack_load_chunk __ ("chunk-containing-module.js"). Then (() => __webpack_require __ (" ./module ")) 1 __webpack_load_chunk __ (" chunk-containing-module.js "). then (() => __webpack_require __ (" ./ module ")) In most cases this cannot be changed, but the webpack command considers some cases where webpack could generate a block that directly executes the contained module.  This can result in less code generated.  ESM imports and exports While there is already a plugin for generating ESM exports, the webpack team is considering adding built-in support for this feature, which may be useful when you decide to integrate webpack packages into ESM boot environments or inline scripts.  JavaScript.  Quick Start Learn the basics of JavaScript with a hands-on example of building a web application Learn More The command also takes absolute URLs into account when importing.  This is very useful when using external services that offer their APIs as EcmaScript modules.  Here's an example: JavaScript import {event} from "https://analytics.company.com/api/v1.js" // Changes to: import ("https://analytics.company.com/api/v1.js" ) 12345 import {event} from "https://analytics.company.com/api/v1.js" // Changes to: import ("https://analytics.company.com/api/v1.js") Such the function will help to gracefully handle errors with external dependencies.  ESM Library The webpack team will also try to improve the bundling using the ESM libraries and will add a special mode that does not apply chunking, but instead generates rendered modules that can be plugged in via ESM imports and exports.  This means that as long as loaders, graphics modules, and resource optimizers are running, no fragment graphs will be created.  Instead, each module in the modules graph will be released as a separate file.  Strict Mode Caveats Sooner or later, the webpack team plans to ensure that all contained code is put into strict mode when the ESM package is created.  While this may not be a problem for many modules, there are a few older packages that may have problems with different interpretations, so it would be nice to see warnings for them.  SourceMap Performance SourceMap provides a way to map code in a compressed file back to its original position in the original file.  In other words, it links the minified version of the resource (CSS or JavaScript) to the original authoring version.  This utility helps you debug applications even after resources have been compressed / optimized.  Using SourceMap in webpack is currently quite expensive due to performance issues, so the webpack team will be looking to improve this in 2021.  They will also be looking to update / improve the terser plugin, which is the default webpack minifier in webpack 5. Package.json export / import field Node.js v14 came with support for an export field in package.json.  This feature allows you to directly define entry points for a package, or conditionally define entry points for each environment or JavaScript flavor (TypeScript, Elm, CoffeeScript, etc.).  In a later release, private imports were also supported in Node.js (similar to the export field in package.json).  For now, webpack 5 only supports the export function, even with additional conditions such as specifying production / development.  Import fields for private imports are another feature to look out for in 2021.  HMR for Modular Design Hot Module Replacement (HMR) works by replacing, adding, or removing modules while the application is still running, without the need for a complete reboot.  This can significantly speed up development by preserving application state that would have been lost on a hard reboot.  Plus, it instantly refreshes the page when changes are made to the source code, much like changing styles directly in the browser developer tools.  Webpack 5 ships with a new feature called “Module Federation”.  This feature allows you to integrate multiple assemblies together at runtime.  HMR currently only supports one assembly at a time and updates cannot move between assemblies.  The webpack team will work to improve the HMR updates to move between different builds, making it easier to develop federation apps.  Hint System To monitor errors and warnings, the webpack team is considering adding another category for the user: hint.  Similar to displaying errors and warnings, a tooltip notifies the user of information that may be of value to him.  However, unlike the previous categories, the prompt will identify optimization opportunities or tricks, not problems.  An example hint might look something like: "Did you know that when you add X a change to file Y, you can clean it up?";  or "Easy to encode the space with the space function."  WebAssembly According to the official documentation, WebAssembly (abbreviated Wasm) is "a binary instruction format for a stack-based virtual machine."  This means that you can build your software with programming languages ​​like Rust, C ++ and Python and provide it to the end user in a browser with near-native performance.  In the current version of webpack, WebAssembly is experimental and not enabled by default.  The default support is what the webpack team will hopefully add this year.  Conclusion There are big changes coming to webpack in 2021, and while this list may not be final, we can look forward to new features and capabilities that will make webpack easier and more efficient.  Author: Elijah Asaolu Source: blog.logrocket.com Editorial: The webformyself team.  JavaScript.  Quick Start Learn the basics of JavaScript with a hands-on example of building a web application Learn More Webpack.  The Basics Watch the Webpack Video!  Look

From the author: Optimizing SVG (Scalable Vector Graphics) for web projects has two benefits: smaller file size and easier work with. But many times I opened a web project and found that SVG assets could be made significantly smaller with simple optimizations. In this article, I will walk you through my process for optimizing SVG assets. This can help you if you are a designer or developer new to working with SVG on the Web.

Many icon libraries provide SVG resources that are already well optimized. But if you are creating your own graphics or provided by another designer, you can do so in a few steps. I mainly use Adobe Illustrator to create and edit SVGs. Here’s a pretty simple icon created in Illustrator:

Optimizing SVG for the Web

We can save it by going to File> Save As and choosing the SVG option. However, if we look at the code of the saved SVG, we can see that it is rather bloated. The code contains a lot of unnecessary data – groups that can be collapsed, paths that can be combined, metadata generated by the program itself, and much more:

JavaScript. Fast start

Learn JavaScript basics with a hands-on example of building a web application

Learn more

Each graphics program has its own way of saving SVGs, but no matter which one you use, the code can still contain a lot of additional data if not optimized. Let’s take a look at some of the ways to fix this problem.

Package launch

SVGO is an NPM package that starts the optimization process for SVG resources at build time, and it’s a good idea to use something like this in your workflow. But the visual tool is often better at removing unnecessary paths and groups and allows us to tweak (and view) optimization parameters depending on what kind of result we want to get.

Quick solution with SVGOMG

One way to quickly remove much of this unnecessary data is with Jake Archibald’s SVGOMG tool. You can either load the SVG file or paste the code directly, and depending on the options you choose, the SVG will be greatly reduced. You may have to experiment with different options to get the desired result, especially if your SVG is quite complex, but I usually find that for simple icons I can turn on most of the options without negatively impacting the result.

Optimizing SVG for the Web

By running the code through SVGOMG, we get the following:

This is much better than leaving the graphic unoptimized, but it contains an extraneous element. And if the original SVG contains groups, layers and effects, then there is a limit to how much a tool like SVGOMG can optimize it. It’s much better if we go back to the graphics program and make some changes before running it through the optimization tool.

Editing SVG

Knowing how to write SVG code will help you get the cleanest and most minimized result. Check out the MDN documentation for a guide to drawing SVG paths and this video by Haydon Pickering if you would like more information.

But for the vast majority of us, SVG editing is only possible with a visual tool. I’m using Adobe Illustrator for this example, but other tools like Sketch have similar editing functionality.

How much code you can remove by editing SVG depends on its complexity and use case. The following tips usually apply to icons and simple graphics. Complex illustrations often cannot be edited to this extent without affecting the final result – and in some cases it may be better to use PNG or JPG.

Expand Groups

The first thing I do when optimizing my SVG is to remove all hidden layers and expand the groups where possible. This removes all path groups in the tags of the SVG code. You might want to keep some of the groups if you plan to style or animate them. You can expand the group in Illustrator with the keyboard shortcut Shift + CMD + G.

Optimizing SVG for the Web

Convert to outlines

Then I convert all strokes to paths where possible (Fig 04). In Illustrator, we can do this using Object> Extend. There may be some exceptions: if you style or animate stroke-dasharray or stroke-dashoffset, you need to leave them intact, and also if you want to keep the stroke width when scaling the SVG.

Optimizing SVG for the Web

You can also use the Flip option in Illustrator to transform areas of an image, such as simple drawings, into individually selectable paths. For complex or detailed patterns, it may be best not to.

Convert text to outlines

It is sometimes useful to convert text to outlines if the text is purely decorative or the content will be conveyed in another way, such as with a title, button text, or aria-label. While it’s helpful to use the SVG element, it doesn’t always make sense, especially if you need to load a different web font to display the SVG text. We can convert text to paths in Illustrator by selecting it and clicking Type> Convert To Paths.

Combining paths

Now that everything in our SVG is paths, we can merge them to reduce their number. Take the search icon as an example: two intersecting paths can be combined into one to create a single path.

JavaScript. Fast start

Learn JavaScript basics with a hands-on example of building a web application

Learn more

To combine paths in Illustrator, we select them and use the combine option from the PathFinder menu.

An exception is the scenario where we want to style or animate the paths separately – in which case they should not be merged.

Optimizing SVG for the Web

Remove additional paths or groups

When the paths are merged, I do a final layer check and remove any empty layers or duplicate paths that may have been created in the process.

Fitting the artboard

When I use SVG icons in HTML, I don’t want to leave extra space around them that I can’t get rid of. This can happen when the SVG viewBox is larger than the content. In Illustrator, I choose Object> Artboards> Fit To Artboard to make the viewBox fit the artwork.

Optimizing SVG for the Web

Export

We are now ready to save the SVG. In Illustrator, we can choose File> Save As and choose SVG as the format. In the window that appears, we will be offered several SVG options. I usually select “Presentation Attributes” to tweak the styling options.

SVG is now ready to run through the optimization tool. For icons, I can usually tweak most of the parameters in SVGOMG. You will notice that the code is much cleaner! But even that doesn’t always remove everything that can be removed. In the code below, I still have an empty element, so it’s worth doing one more final manual cleanup and removing it in the code editor. The SVG is now ready to use!

Using SVG

SVG can be used on the web in a variety of ways, including:

In the img tag

In the CSS property background-image

Inline in HTML

Sprites

In particular, inline SVG icons provide the most performance and flexibility, and the best way to use them is by creating a sprite. If you don’t want to do it manually, there are NPM packages available that automatically generate SVG sprites. Icomoon is an app that offers a similar service.

Then, when it comes to using them, instead of pasting the entire SVG, we can reference them using the element:

Since we are using outlines, we can use the following CSS to instruct all files to inherit the current color, rather than use the fill property: the SVG icon used in the button will simply inherit the button text color.

We need to remove the fill attribute of the SVG itself during the optimization process in order to style it that way with CSS.

Conclusion

It looks like a lot of steps, but in fact the whole process takes surprisingly little time if you are familiar with the graphics program. After a few repetitions, this is fixed in the muscle memory. I like to optimize most SVG icons in batches at the start of the project. It’s worth taking a little time ahead of time to make it easier to work with graphics in the future.

Author: Michelle barker

A source: //css-irl.info

Editorial staff: Webformyself team.

JavaScript. Fast start

Learn JavaScript basics with a hands-on example of building a web application

Learn more

Web design. Fast start

Take a course and learn how to design and prototype a website in Figma!

Watch the video

Leave a Reply

Your email address will not be published. Required fields are marked *