document.currentScript和import.meta

2020-08-272737次阅读javascript

Document.currentScript属性返回当前正在运行的脚本所属的<script>元素。调用此属性的脚本不能是JavaScript模块,模块应当使用import.meta对象。

 

document.currentScript

值得注意的是,如果当前正在执行的代码是被其他代码作为回调函数或者事件处理函数调用的,那么currentScript属性不会指向任何<script>元素,而是会返回null。这个属性只在脚本被解析后首次运行时有效。

<script type="text/javascript" async>

      if (document.currentScript.async) {
        console.log("Executing asynchronously");
      } else {
        console.log("Executing synchronously");
      }
</script>

 

import.meta

import.meta是一个给JavaScript模块暴露特定上下文的元数据属性的对象。它包含了这个模块的信息,比如说这个模块的URL。

<script type="module">
import './index.mjs?someURLInfo=5';
</script>
// index.mjs
new URL(import.meta.url).searchParams.get('someURLInfo'); // 5

 

上一篇: DOM中Element.closest()方法  下一篇: html-webpack-plugin插件生成多个html页面引入不同的js文件  

document.currentScript和import.meta相关文章