GithubHelp home page GithubHelp logo

thasmo / external-svg-polyfill Goto Github PK

View Code? Open in Web Editor NEW
6.0 1.0 2.0 108 KB

Small and basic polyfill to support referencing external SVG files.

License: MIT License

HTML 26.53% JavaScript 5.54% TypeScript 67.93%
polyfill svg external npm browser inline embed legacy fallback

external-svg-polyfill's Introduction

External SVG Polyfill npm CDN

Small and basic polyfill to support referencing external SVG files

Browser like IE9-IE11, Edge12, Safari 5.1-6, or UCWeb11 do not support referencing external files via location hash. Referencing external files can be especially useful when dealing with a technique called SVG sprites, where multiple SVG elements are stored within a single SVG file. It is possible to inline these SVG sprites into the HTML document itself, but this has several disadvantages i.e. caching issues, unneeded HTML file size growth, development inconveniences, etc. Externally referenced SVG sprites mitigate those problems but are not supported in the mentioned browsers.

external-svg-polyfill embeds referenced SVG files automatically.

Features

  • User-agent sniffing is used to determine feature support.
  • External SVG files are fetched via xhr and embedded while use elements are updated.
  • Cross-domain SVG files are fetched and embedded for all browsers to work around browser limitations.
  • To prevent naming collision issues, id attributes are updated to use a unique name.
  • Dynamically added SVG use elements are processed upon changes in the DOM.
  • Various lifecycle events get dispatched on relevant DOM elements.
  • Minified file size is below 5 KiB to keep the load, parse and execution times low.
  • Script is not self-executing, it needs to be called explicitly.
  • Project is written in TypeScript.

Setup

Installation

npm

npm install @thasmo/external-svg-polyfill

CDN

<script src="https://cdn.jsdelivr.net/npm/@thasmo/external-svg-polyfill@3/browser/bundle.min.js"></script>

Usage

Just define some svg use elements in the HTML markup and let external-svg-polyfill do the rest.

Static Website

<!doctype html>
<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/@thasmo/external-svg-polyfill@2/browser/bundle.min.js"></script>
        <script>
            window.document.addEventListener('DOMContentLoaded', function() {
                new ExternalSvgPolyfill();
            });
        </script>
    </head>
    <body>
        <svg xmlns="http://www.w3.org/2000/svg">
            <use href="/static/sprite.svg#icon"></use>
        </svg>
    </body>
</html>

Web Application

import ExternalSvgPolyfill from '@thasmo/external-svg-polyfill';
new ExternalSvgPolyfill();

API

method description
run Run the polyfill manually if the run option is set to false.
observe Start observing the DOM for changes if the observe option is set to false.
unobserve Stop observing the DOM for changes.
destroy Stop the polyfill, stop observing and restore the original markup.
detect Run browser detection manually if the detect option is set to false.

Options

option description type default
target SVG use elements to process. string, SVGUseElement[], NodeListOf<SVGUseElement> svg use
context Element within to search for SVG use elements. HTMLElement window.document.body ?: window.document.documentElement
root Element to which prepend SVG embeds to. HTMLElement window.document.body ?: window.document.documentElement
run Run the polyfill on object instantiation. boolean true
prefix Prefix id attribute values to ensure uniqueness. false won't change the attributes. boolean true
detect Detect browser-support automatically. false will run the polyfill in any browser. boolean true
observe Observe DOM changes within the context element and rerun the polyfill. boolean true
crossdomain Embed crossdomain SVG files for all browsers regardless. boolean true
namespace Namespace of the dispatched events. string external-svg-polyfill
agents Array of regular expressions matching relevant user agents to polyfill. RegExp[] [/Edge\/12/, /Version\/6\.0.+Safari/, /UCBrowser\/11/]

Events

All event are prefixed with the namespace option, are bubbling and can be cancelled using event.preventDefault().

event description data
external-svg-polyfill.load An external SVG file is loaded via xhr. address
external-svg-polyfill.insert An external SVG file is inserted. address, file
external-svg-polyfill.remove An external SVG file is removed. address
external-svg-polyfill.apply An SVG use element's href attribute is updated. address, identifier
external-svg-polyfill.revoke An SVG use element's href attribute is restored. value

Compatibility

external-svg-polyfill can polyfill these browsers:

  • Internet Explorer 11 tested
  • UCWeb 11 untested

Alternatives

Some alternatives exist and, in fact, external-svg-polyfill was greatly inspired by them. Check them out!

Resources

Credits

BrowserStack
BrowserStack loves open source and provides free manual and automated testing for this project! ❤️

License

MIT license

FOSSA Status


forthebadge

external-svg-polyfill's People

Contributors

p-ham avatar thasmo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

p-ham fossabot

external-svg-polyfill's Issues

Module not found

After upgrading from Webpack Encore 0.33 to 1.7.0 I have the following error:

> encore production
Running webpack ...
 WARN  Compiled with 1 warnings7:47:55 AM
 warn  in ./packages/theme/Resources/Private/Js/main.js7:47:55 AM
export 'default' (imported as 'ExternalSvgPolyfill') was not found in '@thasmo/external-svg-polyfill' (module has no exports)
 ERROR  Failed to compile with 1 errors7:47:55 AM
Module build failed: Module not found:
"./node_modules/@thasmo/external-svg-polyfill/module/index.js" contains a reference to the file "./core/Polyfill".
This file can not be found, please check it for typos or update it if the file got moved.
Entrypoint main = runtime.f831b087.js 189.1818b934.js 800.6b815a86.js main.7c7f9bd6.css main.bb64df66.js 73 auxiliary assets
webpack compiled with 1 error and 1 warning

The main difference is, that Webpack Encore 1.x uses Webpack 5 instead of Webpack 4.

workaround

When I change the import from

export { default } from './core/Polyfill';

to

export { default } from './core/Polyfill.js';

it works fine.

Also: when I remove "type": "module", from your npm-package's package.json - it compiles fine too.

I know that in Webpack 5 something changed about Node modules loading. But I thought that referes only to old "require" statements and default Node.js modules like "path" and so on.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.