Generate SVG Skeleton of a Web Page Using JavaScript
XHR and its related features have been commonly used in recent decades. Since then, more and more Web sites now represent as Web Apps. To improve user experience with progressive loading, many Apps use skeleton screen to ease the feelings of unknown, rather than serve a blank white screen while waiting.
What is a Skeleton Screen
It’s the gray shapes shown while the data is loading from the server instead of displaying a classical spinner. —-^What is a skeleton screen 💀?
What for
Look at this comparison, UI with skeleton seems to have less reflow which I think is more comforting.
This image referred from ^What is a skeleton screen 💀?
Types of Skeletons
Element + CSS
Check https://freefrontend.com/css-skeleton-loadings/
Image(non-SVG)
Just a different type of image representation depends on what your designers gave. Used as background image or source of an image element.
SVG
The Structure of a SVG file is very similar to a HTML file because they both are XML-based file format. Also, a SVG file can be rendered directyly in a HTML without using <img>
or background-image
CSS.
Here is a example for rendering a rectangle:
1 | <div style="width: 100px; height: 100px; background-color: red;"> |
1 | <svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> |
HTML | SVG |
---|---|
For more attributes, check https://www.w3schools.com/graphics/svg_rect.asp
Easy, right?
How to Generate SVG from HTML
Full code in https://github.com/LynanBreeze/web-skeleton-generator
- Foreach HTML DOM tree nodes, from top to bottom, from outside to inside, collect sizes and positions
- Add
rect
node to SVG File when DOM node is a leaf node or it’s has background color - Wrap these
rect
nodes in a<svg>
tag - Done~
Visualized process looks like this ⬇️:
Some nodes should be skipped, such as:
- Non-media element with no background (most of them are placeholder elements)
<a>
with no style or with only 1 child element
Generate SVG Skeleton of a Web Page Using JavaScript