javascript - 将外部脚本嵌入到 Next.js 应用程序中

标签 javascript html reactjs next.js

我一直在尝试将外部 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 to document.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/

相关文章:

javascript - 在文本区域中指示自动换行

javascript - ExtJS - 如何仅对文本的一部分进行着色

html - Firefox 中菜单项之间的空间

javascript - 为具有不同索引的js函数创建循环

javascript - 如何删除数组中对象的数组中的对象?

javascript - 更改 react 大日历事件的颜色

javascript - 通过拖放响应大日历

javascript - Jquery的change()函数

javascript - 使用 Google Apps 脚本为 google 文档表自定义边框

javascript - componentDidMount 意外 token 错误 [React.js]