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

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

上周翻阅技术周刊时,偶然看到一个 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

display: none;与visibility: hidden;的区别

display:none;会让元素完全从渲染树中消失,渲染的时候不占据任何空间;visibility: hidden;不会让元素从渲染树消失,渲染师元素继续占据空间,只是内容不可见,display: none;是非继承属性,子孙节点消失由于元素从渲染树消失造成,通过修改子孙节点属性无法显示;

属性设置百分比时的计算参考汇总

元素宽高width,min-width,max-width等元素宽度设置百分比,以包含块的宽度为标准进行计算;height,min-height,max-height等元素宽度设置百分比,以包含块的高度为标准进行计算;

readonly与disabled的区别

readonly 只对 <input> 和 <textarea> 标签有效;disabled 对所有表单元素都有效, 包括:<input>, <textarea>, <button>, <label>, <option>, <select>等

css的overflow属性

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

Vue Prop属性功能与用法实例

这篇文章主要介绍了Vue Prop属性功能与用法,结合实例形式较为详细的分析了vue.js中Prop属性的功能、原理、使用方法及相关操作注意事项,写的十分的全面细致,具有一定的参考价值

深入剖析z-index属性

层叠顺序的大小比较;层叠顺序级别高的元素覆盖级别低的元素。首先要注意,z-index:auto 虽然可以看作z-index:0 ,但是这仅仅是在层叠顺序的比较上;从层叠上下文上讲,二者有本质差别:auto 不会创建层叠上下文,z-index:0 会创建层叠上下文。

Vue.js-计算属性和class与style绑定

所有的计算属性都以函数的形式写在Vue实例中的computed选项内,最终返回计算后的结果。在一个计算属性中可以完成各种复杂的逻辑,包括运算、函数调用等,只要最终返回一个结果即可。

css属性分类介绍

CSS分类目录 文本/字体/颜色 文本相关 字体相关 颜色相关 背景相关 大小/布局 大小属性 margin 外边距 padding 内边距 border 边框 position 定位 列表/表格 多列属性 可伸缩框属性 列表属性 Grid属性 Table属性 动画属性 Animation 动画属性 Transition 过渡属性

css中word-wrap white-space word-break textoverflow的使用

word-wrap正常来说,在一行文本中,如果出现这一行已经放不下的单词,浏览器会自动将该文字转入下一行。white-space规定段落中的文本不进行换行。

css使用到的border边框属性

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

点击更多...

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