如何使用"下一个脚本"精确控制脚本标记的插入位置



我目前正在尝试将第三方脚本添加到我的Next.js应用程序中。脚本在脚本标记的正下方插入一个iframe。因此,我需要精确控制脚本标记在页面上的位置。

我目前正在使用next/script,因为常规脚本标记会阻止iframe的呈现。然而,next/script标记似乎根据所使用的策略重新定位脚本:使用beforeInteractive策略将脚本插入头部。afterInteractive和lazyOnload将其插入页面底部附近的某个位置。

如果我有以下内容:

<div id="script-container">
<Script id="script" async /* other attributes */ />
</div>

当页面加载时,我如何确保脚本保持在脚本容器div中?

这是我想出的一个有点棘手的解决方案。

import React, { useRef } from 'react'
import Script from 'next/script'
export const ScriptComponent = (props) => {
const containerRef = useRef(null)
function moveScript() {
containerRef.current.appendChild(this)
}
return (
<div ref={containerRef} id="script-container">
<Script
id="script"
type="text/javascript"
src="#url"
async
onLoad={moveScript}
/>
</div>
)
}

基本上添加一个onLoad函数,将脚本移回容器。我不确定这个解决方案的整体一致性,因为它取决于在加载iframe之前移动的脚本,但它似乎与我正在使用的脚本配合使用。

最新更新