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
403 views
in Technique[技术] by (71.8m points)

javascript - SVG <script> element: inside or outside?

I see <script> tag can be used within svg tag (ref). Also, the elements within svg tag is accessible through JavaScript outside the tag as they are part of DOM. I could not find much details on which is better. Normally, I keep all the JS code in separate file and include the reference in html. Can I do the same with script targeted to svg elements as well. Also, I read I can also give a link to an external JS file inside the svg tag.

To be more clear, Say I have a webpage (html5) with embedded svg tag in it. the svg contained few basic shapes, which I need mouse interaction. I may use jQuery, but not other external plugin. Would u recommend keeping all the JavaScript (for elements outside and inside svg) in one single file, or keep the svg part separate. Also is it ok to refer to the elements within the svg tag using jQuery? Any inefficiency if I do it?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Placing a <script> element inside SVG (whether you use code inline or referenced in another file via xlink:href) is correct when your script is appropriate for the SVG itself, with or without another context it may be placed within. This is necessary, for example, if you have just a scripted SVG document.

For example, let's say you have an HTML page and you include two SVG files.

  • The first SVG file has some custom animation created through JavaScript. This SVG file should have its own script element directly.

  • The second SVG file is just a fancy image, and you want to make it so when you click on that image a form on your HTML page is submitted. For this, the script should be in your HTML page, since it talks to both the SVG and your HTML form. Here's a similar example, where buttons in the HTML are used to control the SVG.

The line becomes fuzzier when you are inlining your SVG content in something XHTML5, instead of referencing an external SVG file. Is that SVG content its own beast, or is it just as much a part of the HTML page as a particular paragraph of text?

I personally tend to inline my SVG into the HTML and thus keep all my script outside the SVG. Either will work, though.


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

...