我忽视了 document.currentScript 多年——你别再错过

摘要:上周翻阅技术周刊时,偶然看到一个 DOM API:document.currentScript。起初我以为又是一个“用不上”的浏览器接口。结果一上手才发现,它悄悄强大,专治那种“这个脚本到底从哪儿加载的?”的抓狂时刻。

上周翻阅技术周刊时,偶然看到一个 DOM API:document.currentScript。起初我以为又是一个“用不上”的浏览器接口。结果一上手才发现,它悄悄强大,专治那种“这个脚本到底从哪儿加载的?”的抓狂时刻。


它是干什么的?

document.currentScript 会返回当前正在执行的 <script> 元素。把它想成脚本在运行中照的一面镜子:你能读到自身来源、属性,甚至临时打上标记,按需调整行为。

<script>
  console.log("tag name:", document.currentScript.tagName);
  console.log(
    "script element?",
    document.currentScript instanceof HTMLScriptElement
  );

  // 打印当前脚本的 src
  console.log("source:", document.currentScript.src);
  // 给脚本标签加个自定义属性
  document.currentScript.setAttribute('-webkit-tap-highlight-color: transparent; margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; visibility: visible;">, 'true');

  // tag name: SCRIPT
  // script element? true
</script>

这段代码能记录脚本的来源 URL、加自定义属性等。更棒的是:现代主流浏览器都支持。

再看一个例子:

<script -webkit-tap-highlight-color: transparent; margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important; visibility: visible;">="123urmom" defer>
  console.log("external key:", document.currentScript.dataset.externalKey);

  if (document.currentScript.defer) {
    console.log("script is deferred!");
  }
</script>

<!-- 输出:
external key: 123urmom
script is deferred!
-->


两个需要特别当心的点:模块与异步

1) type="module" 时不可用

**模块脚本中 document.currentScript 始终是 null**:

<script type="module">
  console.log(document.currentScript);
  console.log(document.doesNotExist);

  // null
  // undefined
</script>

2) 异步回调里也拿不到

离开同步执行栈(比如 setTimeout 回调里),它就不是“当前脚本”了:

<script>
  console.log(document.currentScript);
  // <script> 标签对象

  setTimeout(() => {
    console.log(document.currentScript);
    // null
  }, 1000);
</script>


一个比你想的更常见的场景

在很多 CMS 平台里,你不能随意改 <script> 内容,但又需要给共享脚本传配置(比如第三方库的 key、模式等)。

常见做法:用 data- 属性传参。难点在于:如何优雅地拿到这个脚本标签本身的 data- 值? 答案就是 document.currentScript:

<!-- 共享库需要配置 -->
<script
  -webkit-tap-highlight-color: transparent; margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important;">="{{pricingTableId}}"
  -webkit-tap-highlight-color: transparent; margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important;">="{{publishableKey}}"
>
  const scriptData = document.currentScript.dataset;

  document.querySelectorAll('[-webkit-tap-highlight-color: transparent; margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important;">).forEach(table => {
    table.innerHTML = `
      <stripe-pricing-table
        pricing-table-id="${scriptData.stripePricingTable}"
        publishable-key="${scriptData.stripePublishableKey}"
        client-reference-id="picperf"
      ></stripe-pricing-table>
    `;
  })
</script>

干净、无全局变量污染、也不需要专有约定


其它好用的应用方式

1) 写库时做加载方式/位置校验

你的库需要异步加载?可以在入口就校验:

<script defer src="./script.js"></script>
<!-- script.js -->
if (!document.currentScript.async) {
  throw new Error("This script must load asynchronously.");
}
// ...库的其它逻辑

强制脚本出现在 <body> 起始处之后也可以这样做:

const isFirstBodyChild =
  document.body.firstElementChild === document.currentScript;

if (!isFirstBodyChild) {
  throw new Error(
    "This MUST be loaded immediately after the opening <body> tag."
  );
}

2) 调试脚本来源

复杂页面里追溯“这段脚本从哪儿引入的”很常见:

console.log(`Script: ${document.currentScript.src}, ID: ${document.currentScript.id}`);

3) 按属性做条件分支

让同一段脚本在不同页面/环境下有不同行为:

<script -webkit-tap-highlight-color: transparent; margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important;">="production">
  if (document.currentScript.dataset.env === 'production') {
    console.log('Production mode activated');
  }
</script>

小结

document.currentScript 是个低调但实用的 API:

  • 同步脚本里,可直接拿到当前 <script> 元素;
  • 适合从标签-webkit-tap-highlight-color: transparent; margin: 0px; padding: 0px; outline: 0px; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important;">、调试来源、做加载方式/位置约束;
  • 记住:**模块脚本与异步回调中为 null**。
来源:大迁世界

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_12885