Skip to content

DavidS-Repo/safe-svg-loader

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 

Repository files navigation

SVG-to-JS Loader

A slim Python script that converts every .svg file into a _load.js file.
Each loader builds the SVG with createElementNS, so it works even when your site enforces require-trusted-types-for 'script' in CSP.


How it works

  • Walks through the current folder (and sub-folders) looking for .svg files.
  • Parses each SVG with Python’s xml.etree.ElementTree.
  • Emits JavaScript that recreates every tag, attribute, and text node with document.createElementNS.
  • Saves the result as name_load.js next to the original SVG.

The loader waits for DOMContentLoaded, finds an element whose id matches the SVG file name, and appends the SVG tree there.


Quick start

# put make_loaders.py next to your SVGs
python make_loaders.py

This writes files like:

logo.svg      ->  logo_load.js
rocket.svg    ->  rocket_load.js

Add to your page

<!-- element id MUST match the svg file name -->
<div id="logo"></div>
<script src="logo_load.js"></script>

<div id="rocket"></div>
<script src="rocket_load.js"></script>

Now you can style elements inside the SVG:

#rocket .flame {
  animation: flicker 0.3s infinite alternate;
}

Options

Open make_loaders.py to tweak:

  • output folder
  • whether to recurse into sub-folders
  • attribute filters or transforms

The script is plain Python 3 with no external packages.


Why not use <img>?

Using <img src="logo.svg"> blocks external CSS from targeting the SVG’s internal classes. Inline SVG fixes that, but inline markup is disallowed under strict CSP. These loaders give you inline power without breaking policy.


License

MIT

About

Python script that turns every SVG in a folder into a _load.js file. Each loader builds the SVG with createElementNS and drops it into a div whose id matches the file name. No innerHTML, so it works with strict CSP and Trusted Types.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages