shakyShane / gulp-svg-sprites

Create SVG sprites or compile to <symbols>
MIT License
334 stars 45 forks source link

Consider providing a JS loading script #52

Closed davidtheclark closed 7 years ago

davidtheclark commented 10 years ago

What would you think about providing a JS loading script when the sprite is generated?

I'm using the <symbol> pattern, and instead of pasting the contents of the SVG file into the head of my doc I'd like to keep the spritesheet external and then inline the contents via AJAX (so the sprite is both cached separately from the page and loaded asynchronously).

(Grunticon, for example, generates a simple loading script and provides it along with the other generated resources. Or here's an example somebody wrote for grunt-svgstore: https://gist.github.com/w0rm/621a56a353f7b2a6b0db.)

shakyShane commented 10 years ago

Sounds like a great idea :)

I would be grateful if you, or anyone else could provide a JS snippet that works with this library?

That would help me implement this a lot quicker.

Thanks

shakyShane commented 10 years ago

...plus details on how to use it would be awesome

davidtheclark commented 10 years ago

Great. I will try to get around to creating a pull request sometime soonish.

davidtheclark commented 10 years ago

Here's the snippet I was using myself:

(function (window, document) {
    /**
     * Get the SVG symbols and plug them into the DOM for <use>.
     * Defer until DOMContentLoaded, because it is an enhancement.
     */
    window.addEventListener('DOMContentLoaded', function (event) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/assets/svg/symbols.svg', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                var resultEl = document.createElement('div');
                resultEl.style.display = 'none';
                resultEl.innerHTML = xhr.responseText;
                document.body.appendChild(resultEl);
            }
        };
        xhr.send();
    });
})(window, document);

I may or may not have time coming up to figure out how things work in the plugin and create an intelligent pull request --- so I just thought I'd post the snippet here in case anybody else wanted to jump on it. Or if anybody has any opinions about the snippet and knows of better ways of doing things, that would be awesome.

This could be a template with the path to the SVG file as a variable, everything else unchanging; and it could be uglified and minified to it's ready to copy-paste.

It would only work on IE9+, which should be fine given SVG support, I think.

soenkekluth commented 7 years ago

we only provide the core generation of the svg sprite - this should not be part of it