我一直在尝试将外部 JavaScript 源代码嵌入到我的 Next.js 应用程序中,但一直收到以下错误:
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
可以找到我尝试使用的代码 here - 带有船只的 map 可以选择嵌入它。到目前为止,生成此错误的组件如下所示:
<div className={styles['container']}>
<Script type="text/javascript">
var width="100%";var height="400"; var mmsi=228402900;
</Script>
<Script
type="text/javascript"
src="https://www.vesselfinder.com/aismap.js">
</Script>
</div>
如果我将嵌入代码复制到 CodePen 中,它就可以正常工作 - link to my codepen with the embedded map here .
有人知道这里可能是什么问题吗?
最佳答案
出现此问题是因为 next/script
正在异步加载外部脚本,因此忽略了 document.write()
脚本中存在调用。
来自 Document.write()
MDN 文档:
Note: Using
document.write()
in deferred or asynchronous scripts will be ignored and you'll get a message like "A call todocument.write()
from an asynchronously-loaded external script was ignored" in the error console.
您需要设置 Script
策略beforeInteractive
所以脚本被添加到<head>
, 并显式设置 defer
属性(property)false
以防止脚本被异步加载。
<Script
type="text/javascript"
src="https://www.vesselfinder.com/aismap.js"
strategy="beforeInteractive"
defer={false}
></Script>
关于javascript - 将外部脚本嵌入到 Next.js 应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72252819/