introduction
可选属性
src
指定外部脚本的URL的字符串,这能够是一个绝对的外部URL或者一个内部路径 .
strategy
这个脚本的加载策略
strategy |
description |
|---|---|
beforeInteractive |
在页面交互之前加载脚本 |
afterInteractive |
在页面可交互之后加载脚本 |
lazyOnload |
在浏览器空闲时加载脚本 |
worker |
在web worker中加载脚本 |
注意到: worker是一个实验性的策略仅仅在next.config.js配置启动之后才能够使用,查看 Off-loading Scripts To A Web Worker. .
OnLoad
在脚本一旦加载之后立即执行的回调方法
注意到onLoad不能够和beforeInteractive加载策略一起使用,考虑使用onReady代替 ..
import { useState } from 'react'import Script from 'next/script'export default function Home() {const [stripe, setStripe] = useState(null)return (<><Scriptid="stripe-js"src="https://js.stripe.com/v3/"onLoad={() => {setStripe({ stripe: window.Stripe('pk_test_12345') })}}/></>)}
OnReady
在脚本完成加载之后 以及妹子组件挂载之后立即执行的js回调方法
import { useState } from 'react'import Script from 'next/script'export default function Home() {return (<><Scriptid="google-maps"src="https://maps.googleapis.com/maps/api/js"onReady={() => {new google.maps.Map(ref.current, {center: { lat: -34.397, lng: 150.644 },zoom: 8,})}}/></>)}
OnError
如果一个脚本加载失败之后,执行的方法
onError不能够与beforeInteractive加载策略一起使用 ..
import Script from 'next/script'export default function Home() {return (<><Scriptid="will-fail"src="https://example.com/non-existant-script.js"onError={(e) => {console.error('Script failed to load', e)}}/></>)}
