Skip to content

Separate <defs> from <template> #5

@sidewayss

Description

@sidewayss

Breaking out the template's <defs> into a separate SVG file would have these advantages:

  1. Different shapes/styles for different pages on the same site
  2. In theory, it's more efficient to have only one set of DOM definitions instead of repeating the <defs> in every shadow DOM, but I'm not sure if shadow DOM elements have visibility to a defs in the DOM.
  3. Both files would be more readable than the current single file

But how do you load a single <defs> for the page? You don't want to force the page to include some additional script file. It has to be done from inside BaseElement. The solution that comes to mind is:

class BaseElement {
    static #defsLoaded;                 // new static boolean
    constructor(template, name) {       // new name argument
        if (!BaseElement.#defsLoaded) {
            fetch(`defs-${name}.svg`)   // ...fall back to /html-templates
              .then(rsp => {            // ...fall back to /html-elements
                if (rsp.ok) {
                    rsp.text.then(text => {
                        const parser = new DOMParser;
                        document.insertBefore(parser.parseFromString(text), 
                                              document.body.firstElementChild);
                        BaseElement.#defsLoaded = true;                    
                    }
                }
            }).catch(err => console.error(err.stack ?? err));
        }
    }
}

Seems like a decent idea to me, but I'm not hurrying to implement it.

The same could be done with the template's <style>, but probably best to put it in this same SVG file instead of fetching a separate CSS file.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions