【发布时间】:2018-10-15 00:08:20
【问题描述】:
我有一个 SVG 文件,它使用 JavaScript 动态定义了它的一些样式和 <defs>。
我在 HTML 文件中使用上述 SVG 文件。
- 如果我自己打开 SVG 文件,它的 JavaScript 就会被执行。
- 如果使用 jQuery,我通过 AJAX 将 SVG 文件包含到 HTML 文件中(将 SVG 附加到 HTML 文档),那么 SVG 的 JavaScript 也会被执行。
- 但是,使用纯 JavaScript:如果我通过 AJAX 将 SVG 文件包含到 HTML 文件中(将 SVG 附加到 HTML 文档)那么 SVG 的 JavaScript 不会被执行强>。
我正在尝试理解并修复该行为。
作为 MCVE:
ajax-callee.svg:
<?xml version="1.0" encoding="UTF-8"?>
<svg version="1.1"
baseProfile="full"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:ev="http://www.w3.org/2001/xml-events"
>
<script><![CDATA[
console.log( 'ajax-callee.svg › script tag' );
/** When the document is ready, this self-executing function will be run. **/
(function() {
console.log( 'ajax-callee.svg › script tag › self-executing function' );
})(); /* END (anonymous function) */
]]></script>
</svg>
ajax-caller-jquery-withSVG.html(工作正常):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>(Check out the console.)</p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$.ajax({
method: "GET",
url: "ajax-callee.svg",
dataType: "html"
}).done(function( html ) {
/** Loading the external file is not enough to have, it has to be written to the doc too for the JS to be run. **/
$( "body" ).append( html );
});
});
</script>
</body>
</html>
ajax-caller-pureJS-withSVG-notworking.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>(Check out the console.)</p>
<script>
/** AJAX CALLER **/
/** When the document is ready, this self-executing function will be run. **/
(function() {
var ajax = new XMLHttpRequest();
ajax.open("POST", "ajax-callee.svg", true);
ajax.send();
/**
* Append the external SVG to this file.
* Gets appended okay…
* …but its JavaScript won't get executed.
*/
ajax.onload = function(e) {
/** Parse the response and append it **/
var parser = new DOMParser();
var ajaxdoc = parser.parseFromString( ajax.responseText, "image/svg+xml" );
document.getElementsByTagName('body')[0].appendChild( ajaxdoc.getElementsByTagName('svg')[0] );
}
})(); /* END (anonymous function) */
</script>
</body>
</html>
- jQuery 的哪些不同之处导致 JavaScript 被执行?
- 如何才能运行包含的 SVG JS?
- 有什么要注意的吗?
仅供参考,我正在尝试使用 SVG,但在我的测试中,为 callee 使用 HTML 文件时的行为是相同的。
【问题讨论】:
标签: javascript jquery html ajax svg