Get data attribute of script tag?

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.


    // 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 

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 

which would let me use this following:

var token = document

Leave a Comment