Search code examples
javascriptjqueryajaxsvgecmascript-5

Load SVG file on click in HTML?


I want to load an external SVG file in an HTML page by clicking.

Now I use a JavaScript:

<script language="javascript">
  <!--
  var state = 'none';
  function showhide(layer_ref) {
      if (state == 'block') {
          state = 'none';
      }
      else {
          state = 'block';
      }
      if (document.all) { //IS IE 4 or 5 (or 6 beta)
          eval( "document.all." + layer_ref + ".style.display = state");
      }
      if (document.layers) { //IS NETSCAPE 4 or below
          document.layers[layer_ref].display = state;
      }
      if (document.getElementById &&!document.all) {
          hza = document.getElementById(layer_ref);
          hza.style.display = state;
      }
  }
  -->
</script>

to screen my SVG with:

<a href="#1" onclick="showhide('div1');">Show/hide Alignment</a>                
<div id="div1" style="display: none;" name="1">
  <object type="image/svg+xml" data="1.svg">1 svg file missing</object>
</div>

This way works, but it requests that all SVG files have to be loaded even if I don't screen it.

Is there a way load the SVG only when I click to show it?


Solution

  • How about this? The code essentially just shows/hides the given div. Additionally, it checks if the div is shown for the first time; in that case, the SVG object is loaded (i.e. created with JS and added to the DOM).

    HTML

    <a href="#" onclick="showhide('div1', '1.svg');">Show/hide Alignment</a>
    <div id="div1" style="display: none;"></div>
    

    JS

    function showhide(id, svg) {
        var element = document.getElementById(id);
        if (element.style.display == "none") {
             // Check if SVG object already loaded; if not, load it now
             if (!element.getElementsByTagName("object").length) {
                 var object = document.createElement("object");
                 object.type = "image/svg+xml";
                 object.data = svg;
                 element.appendChild(object);
            }
            element.style.display = "block";
        }
        else {
            element.style.display = "none";
        }
    }