Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

svg - Reinitialize SVGweb for ajax

I have no problem using SVGweb when page is simply loaded (opened).

How is it possible to reinitialize SVGweb in order to redraw all SVG on the page?

Anotherwords I need SVGweb to rescan and rerender everything on the page.

source (from this):

<script type="image/svg+xml">
  <svg>
    ...
  </svg>
</script>

to this (like SVGweb si doing that when simply open the page):

<svg>
...
</svg>

I need this because I change the SVG graphics using ajax and need to rerender it on the page.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I needed the same capability and figured out how to do this properly without modifying the svgweb source or calling the _onDOMContentLoaded() handler manually. In fact, it is supported natively.

The trick is to (re)attach your SVG elements to the DOM using window.svgweb.appendChild() which causes the node to be processed by svgweb, as is documented within the svgweb manual.

Example, using jQuery:

// Iterate over all script elements whose type attribute has a value of "image/svg+xml".
jQuery('body').find('script[type="image/svg+xml"]').each(function () {
    // Wrap "this" (script DOM node) in a jQuery object.
    var $this = jQuery(this);
    // Now we use svgweb's appendChild method. The first argument is our new SVG element
    //  we create with jQuery from the inner text of the script element. The second
    //  argument is the parent node we are attaching to -- in this case we want to attach
    //  to the script element's parent, making it a sibling.
    window.svgweb.appendChild(jQuery($this.text())[0], $this.parent()[0]);
    // Now we can remove the script element from the DOM and destroy it.
    $this.remove();
});

For this to work properly I suggest wrapping all SVG script tags with a dedicated div, so that when attaching the SVG element it is attached to a parent element containing no other nodes. This removes the possibility of inadvertently reordering nodes during the process.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...