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

更新日期: 2025-08-15 阅读: 929 标签: 属性

上周翻阅技术周刊时,偶然看到一个 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://fly63.com/article/detial/12885

相关推荐

html中的marquee属性

该标签不是HTML3.2的一部分,并且只支持MSIE3以后内核,所以如果你使用非IE内核浏览器(如:Netscape)可能无法看到下面一些很有意思的效果,该标签是个容器标签

vue里的$refs属性

vuejs的极大程度的帮助减少了对dom的操作,他主要通过添加ref属性,但是当获取this.$refs属性时,稍有不注意就会输出undefined导致我们对dom节点的操作报错。this.$refs.xxx为undefined的几种情况记录:

css的overflow属性

事实上我挺长一段时间都没弄清楚overflow:scroll与overflow:auto的差别,今天测试了一下,总算是明白了。visible: 不剪切内容。hidden: 将超出对象尺寸的内容进行裁剪,将不出现滚动条。scroll: 将超出对象尺寸的内容进行裁剪,并以滚动条的方式显示超出的内容。

css使用到的border边框属性

border 在一个声明中设置所有的边框属性。 border-bottom在一个声明中设置所有的下边框属性。border-bottom-color设置下边框的颜色。border-bottom-style设置下边框的样式。

Cookie 的 SameSite 属性

Chrome 51 开始,浏览器的 Cookie 新增加了一个 SameSite 属性,用来防止 CSRF 攻击和用户追踪。Cookie 往往用来存储用户的身份信息,恶意网站可以设法伪造带有正确 Cookie 的 HTTP 请求,这就是 CSRF 攻击。

React 也能“用上” computed属性

初次见到计算属性一词,是在 Vue 官方文档 《计算属性和侦听器》 一节中,文章中是这样描述计算属性的:模板内的表达式非常便利,但是设计它们的初衷是用于简单运算的。在模板中放入太多的逻辑会让模板过重且难以维护。

css常用属性

text-align 属性规定元素中的文本的水平对齐方式。属性值:none | center | left | right | justify;font-size表示设置字体大小,如果设置成inherit表示继承父元素的字体大小值。

JS、Jquery中判断checkbox是否选中

attr()与prop()如何选择:attr()方法返回被选元素的属性值。prop() 方法设置或返回被选元素的属性和值。当该方法用于返回属性值时,则返回第一个匹配元素的值。当该方法用于设置属性值时,则为匹配元素集合设置一个或多个属性/值对。

css z-index属性

z-index 仅适用于定位元素。即 postition 值为 relative, absolute 和 fixed 属性;堆叠顺序是当前元素位于 z 轴上的值。值越大表示元素越靠近屏幕,反之元素越远离屏幕在同一个堆叠上下文中, z-index 值越大,越靠近屏幕。

CSS中的cursor属性

css中的cursor这个属性是用来设置光标形状的。这个属性定义了鼠标指针放在一个元素边界范围内时所用的光标的形状。默认值:auto,继承性:yes,出现版本:css2

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!