43

Say I've got the following script tag:

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

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

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.

bareMetal
  • 425
  • 1
  • 7
  • 20
Shpigford
  • 24,748
  • 58
  • 163
  • 252

6 Answers6

55

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

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

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');
})();

In the host html:

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

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

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');
brice
  • 24,329
  • 7
  • 79
  • 95
10

Use currentScript

Script tag :

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

In example.js file :

let id = document.currentScript.getAttribute('data-id');
let foo = document.currentScript.getAttribute('data-foo');  

console.log(id) // p3PkBtuA
console.log(foo) // bar
bareMetal
  • 425
  • 1
  • 7
  • 20
  • 1
    this is the best answer in my opinion; it even allows you to load the same script multiple times, changing the data-* tags each time. this really helps with reusability – Matt Apr 12 '23 at 21:28
9

That embed.js is being rendered in the DOM, so you have full access to it. Eithergive it an id and use document.getElementById of querySelctorAll or getElementsByTagName

Within your embed.js you could have something like:

  var scripts = document.getElementsByTagName('script');
  for(var i = 0, l = scripts.length; i < l; i++){
    if(scripts[i].src === '//example.com/embed.js'){
      alert(scripts[i].getAttribute('data-id'));
      break;
    }
  }

You get the idea

rgthree
  • 7,217
  • 17
  • 21
3

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

You will have to parse the DOM and look for the corresponding <script> tag and then fetch the attributes from it. Take a look at the document.getElementsByTagName which would allow you to retrieve all <script> elements on the current page. Then loop through the result array returned by this method, match the correct script element using the src attribute and then read the other attributes you are interested in.

var scripts = document.getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
    var script = scripts[i];
    // you might consider using a regex here
    if (script.getAttribute('src') == '//example.com/embed.js') {
        // we've got a match
        var dataId = script.getAttribute('data-id');
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3
var attributeValue = Array.prototype.slice.apply(document.scripts).filter(
     function(script){
         return script.src.indexOf('script.source.com/big/') > -1;
     })[0].attributes["atrributeName"].value;

where script tag is <sript src="www.script.source.com/big/dud/baa.js" atrributeName="some value"><script>

yonatan
  • 595
  • 1
  • 4
  • 18
1
var scripts = document.getElementsByTagName('script'); // load into a variable all the scripts of the page
for (var i = 0; i < scripts.length; i++) { // parse all scripts
        var script = scripts[i];
        if (script.getAttribute('src') == '//example.com/embed.js') {
            alert(script.dataset.id); // Show only specified script
        }
    }
jumpjack
  • 841
  • 1
  • 11
  • 17
Vitalii
  • 11
  • 1