You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SVG加载时调用外部JavaScript文件?

在SVG加载时调用外部JavaScript文件的解决方案

问题背景

有一张SVG图片,需要实现加载时调用外部JavaScript文件,尝试多种方法均未成功:

  • 在<svg>标签的onload属性中添加alert语句可正常执行,但无法直接调用外部JS代码
  • 在<svg>标签后添加标准<script src="https://mycode.js"></script>标签,同样无法加载外部脚本

中间尝试通过XHR请求外部JS文件,仅能获取文件内容但无法执行:

<svg onload="const xhr = new XMLHttpRequest();xhr.open('GET', 'https://external.js');xhr.send(null);">

可行解决方案

通过在onload事件中动态创建<script>标签并插入到页面头部,可实现加载并执行外部JS文件:

<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
 width="474.000000pt" height="316.000000pt" viewBox="0 0 474.000000 316.000000"
 preserveAspectRatio="xMidYMid meet" onload="function loadScript( url ) {let script = document.createElement('script') 
script.type = 'text/javascript'; script.src = url; document.head.appendChild(script); 
} loadScript('https://external.js')">

原理说明

利用DOM API动态创建<script>元素,指定外部JS的资源地址后将其添加到页面<head>节点中,浏览器会自动加载并执行该脚本文件。

内容的提问来源于stack exchange,提问作者ex7lted

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 00:18:24