Home > database >  External SVG not loading media queries
External SVG not loading media queries

Time:06-19

Im currently using external svg that have inline styling applied, however it won't load the styling.

Initially I used an img to include the external svg like so:

<img id="temp" src="https://lw.com/example.svg">

Where the SVG file looked similar to this:

<svg xmlns="http://www.w3.org/2000/svg" role="img" width="300" height="300" aria-labelledby="loading-aria" viewBox="0 0 300 300" preserveAspectRatio="none">
      <style>
        @media only screen and (max-width: 300px) {
          #mini-cart-rect {
            transform: scale(0.9);
          }
        }
      </style>
      <title id="loading-aria">Loading...</title>
      <rect id="mini-cart-rect" x="0" y="0" width="100%" height="100%" clip-path="url(#mini-cart-clip-path)" style="fill: url(&quot;#mini-cart-fill&quot;);"/>
      <defs>
        <clipPath id="mini-cart-clip-path">
            <rect x="79" y="13" rx="3" ry="3" width="160" height="11"/> 
            <rect x="79" y="63" rx="3" ry="3" width="20" height="11"/> 
        </clipPath>
        <linearGradient id="mini-cart-fill">
          <stop offset="0.599964" stop-color="#f3f3f3" stop-opacity="1">
            <animate attributeName="offset" values="-2; -2; 1" keyTimes="0; 0.25; 1" dur="2s" repeatCount="indefinite"/>
          </stop>
        </linearGradient>
      </defs>
    </svg>

But this didn't load the style block at all, so I tried with object instead:

<object type="image/svg xml" id="temp" data="https://lw.com/example.svg"></object>

However this loads the media query but it apply the style no matter the screen size, so it's not working properly. If screen width is 1000px it still applies the (max-width: 300px).

CodePudding user response:

Let it be done by a native JavaScript Web Component <load-file>

  • Load the SVG from an external file
  • Inject SVG Inline into a shadowRoot (no conflicts with any other styled content)
  • inject <style> into shadowRoot

See: Full documation of this <load-file> Web Component

<script src="https://load-file.github.io/element.js"></script>

<load-file src="//load-file.github.io/heart.svg">
  <style shadowRoot>
    svg {
      height:180px; // StackOverflow snippet height
      dispay: block;
      background: lightgreen;
    }
    @media only screen and (max-width: 600px) {
        svg {
          background:pink; // Resize StackOveflow Browser tab to see effect
        }
      }
  </style>
</load-file>

  • Related