且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取脚本标记的数据属性?

更新时间:2023-12-05 20:27:22

对于支持html5的现代浏览器,您可以使用 document.currentScript

For modern browsers that support html5 you can use document.currentScript to get the current script element.

否则,请使用 querySelector() 通过 id 属性选择您的脚本元素。

Otherwise, use querySelector() to select your script element by id or attribute.

请注意,我们不使用 src 属性,因为如果您通过CDN交付或者开发和生产之间存在差异,那么这可能很脆弱环境。

Note that we don't use the src attribute because that can be fragile if you're delivering over a CDN or with differences between development and production environments.

embed.js

(function(){
    // We look for:
    //  A `script` element
    //  With a `data-id` attribute
    //  And a `data-name` attribute equal to "MyUniqueName"
    var me = document.querySelector('script[data-id][data-name="MyUniqueName"]');
    var id = me.getAttribute('data-id');
})();

在主机html中:

<script async 
  data-id="p3PkBtuA" 
  data-name="MyUniqueName" 
  src="//example.com/embed.js">
</script>

这个approcah的缺点是你无法成功嵌入两个相同的脚本。这是一个非常罕见的情况,但可能会发生。

This approcah has the downside that you couldn't successfully embed two identical scripts. This is a pretty rare case, but could happen.

请注意我个人 data-id 来选择脚本而不是传递数据,并将唯一数据放在更具描述性的标记中:

Note that I would personally us data-id to select the script instead of passing data, and would place the unique data in a more descriptive tag:

<script async 
  data-id="MyUniqueName" 
  data-token="p3PkBtuA" 
  src="//example.com/embed.js">
</script>

这将让我使用以下内容:

which would let me use this following:

var token = document
  .querySelector('script[data-id="MyUniqueName"][data-token]')
  .getAttribute('data-token');