获取脚本标记的数据属性? [英] Get data attribute of script tag?

查看:108
本文介绍了获取脚本标记的数据属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下脚本标记:

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

embed.js 文件中,如何我可以获得 data-id 属性的值吗?

Within that embed.js file, how can I get the value of data-id attribute?

我试图保持 embed.js 文件尽可能轻,所以理想情况下它不需要使用某种javascript库。

I'm trying to keep the embed.js file as light as possible, so ideally it wouldn't need to use some sort of javascript library.

推荐答案

对于支持html5的现代浏览器,您可以使用 <$ c获取当前脚本元素的$ c> 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');

这篇关于获取脚本标记的数据属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆