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.
- 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.
# put make_loaders.py next to your SVGs
python make_loaders.pyThis writes files like:
logo.svg -> logo_load.js
rocket.svg -> rocket_load.js
<!-- 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;
}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.
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.
MIT