JavaScript如何在<head>内的两个<script>标签之间传递数据
问题根因
你声明的全局变量本身是支持跨<script>标签访问的,出现undefined是异步执行时序导致的:async函数执行到await fetch时会暂停当前函数执行,先执行后续同步代码。你调用loadSuccess()之后,fetch请求还在等待服务端返回,此时第一个<script>末尾的console.log(customer_email)、第二个<script>内的同步代码都已经执行完毕,此时customer_email还没被赋值,自然返回undefined。等fetch请求拿到结果给变量赋值时,前面的同步代码早就跑完了。
可行解决方案
以下是几种常用的跨<script>使用异步数据的实现方式:
方案1:自定义事件监听(最灵活)
在第一个<script>的数据赋值完成后触发全局自定义事件,第二个<script>监听该事件后再执行依赖邮箱的逻辑:
第一个<script>修改:
var customer_email; async function loadSuccess() { try { const response = await fetch('/.netlify/functions/success', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }) const resData = await response.json() customer_email = resData.session.customer_details.email; // 赋值完成后触发全局自定义事件,携带邮箱数据 window.dispatchEvent(new CustomEvent('customerEmailReady', { detail: customer_email })) } catch (err) { console.error('请求失败:', err) } } loadSuccess();
第二个<script>写法:
// 监听自定义事件,触发后再使用数据 window.addEventListener('customerEmailReady', (e) => { const customer_email = e.detail // 这里写你需要用到邮箱的所有业务逻辑 console.log(customer_email) })
方案2:全局回调函数
提前在第二个<script>中定义处理邮箱的全局函数,第一个<script>拿到数据后直接调用该函数:
第二个<script>提前声明:
// 全局函数,处理所有依赖邮箱的逻辑 function handleCustomerEmail(email) { console.log(email) // 你的业务逻辑写在这里 }
第一个<script>的loadSuccess函数赋值完成后加一行调用:
customer_email = resData.session.customer_details.email; handleCustomerEmail(customer_email) // 直接调用全局回调
方案3:全局Promise等待
把loadSuccess返回的Promise挂载到全局,第二个<script>等待Promise完成后再取变量:
第一个<script>修改:
var customer_email; // async函数本身返回Promise,挂载到window全局 window.customerEmailLoaded = loadSuccess();
第二个<script>写法:
// 等待异步请求完成后再取值 window.customerEmailLoaded.then(() => { console.log(customer_email) // 你的业务逻辑写在这里 })
注意事项
- 你当前的代码没有处理fetch失败的场景,catch之后response可能为undefined,直接取
response.session会抛出JS异常,建议加可选链判断resData?.session?.customer_details?.email确认取值成功后再执行后续逻辑。
内容的提问来源于stack exchange,提问作者haliofin
相关产品推荐
相关产品推荐

