8

Can I use a custom attribute in a script tag such as:

<script type="text/javascript" mycustomattribute="foo">
    // JavaScript
</script>

And then use the contained JavaScript to access the value of mycustomattribute?

Yves M.
  • 29,855
  • 23
  • 108
  • 144
tonejac
  • 1,083
  • 3
  • 18
  • 32
  • I've answered your question, but *why* do you want to do this? If we know why, we may be able to suggest a better option. – T.J. Crowder Jul 21 '13 at 06:39
  • Side note: There's no reason to have the `type` attribute if the type is `text/javascript`, it's just wasted bandwidth. [That's the default](http://www.w3.org/TR/html5/scripting-1.html#attr-script-type), universally. – T.J. Crowder Jul 21 '13 at 06:40
  • Thanks @T.J.Crowder. I am writing an "embed this wine review" widget. Currently I'm using an iframe, but I want something that can flow with the user's site layout better. So I'm using javascript to write the code into the page instead. But I need a reliable way to have the unique id of the user's wine review available to the javascript. (e.g. [link]http://www.napawapa.com/reviews/view/Yp/2006-Opus-One[/link] – tonejac Jul 21 '13 at 06:45
  • If you need the attribute in order to have a unique id, why don’t you just use the `id` attribute? – Jukka K. Korpela Jul 21 '13 at 10:53
  • Just a clarification: not a unique DOM element id, a unique wine id. – tonejac Jul 22 '13 at 15:12

4 Answers4

11

Can I use a custom attribute in a script tag such as:

Yes, using data-* attributes:

<script data-info="the information"...

And then use the contained javascript to access the value of 'mycustomattribute'?

Yes, probably. If you give the script tag an id, you can do it reliably:

var info = document.getElementById("theId").getAttribute("data-info");

Otherwise, you have to make assumptions about the script tag. If it's always in the markup of the page (not added later using code), you can do this:

var scripts = document.getElementsByTagName("script");
var info = scripts[scripts.length - 1].getAttribute("data-info");

That's because if the script tag is in the markup, it's run as soon as it's encountered (unless async or defer is used [and supported by the browser]), and will always be the last script tag on the page (at that point in time). But again, if code adds the script tag later, using createElement and appendChild or similar, you can't rely on that.

Here's a complete example: Live Copy

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Data on Script Tags</title>
</head>
<body>
  <script>
    function display(msg) {
      var p = document.createElement('p');
      p.innerHTML = String(msg);
      document.body.appendChild(p);
    }
  </script>
  <script data-info="first">
    (function() {
      var scripts = document.getElementsByTagName("script");
      var info = scripts[scripts.length - 1].getAttribute("data-info");
      display("Got info '" + info + "'");
    })();
  </script>
  <script data-info="second">
    (function() {
      var scripts = document.getElementsByTagName("script");
      var info = scripts[scripts.length - 1].getAttribute("data-info");
      display("Got info '" + info + "'");
    })();
  </script>
</body>
</html>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Among the assumptions that must be made when getting the "last" script, is this case: http://stackoverflow.com/questions/14409982/is-it-the-last-script-element-the-currently-running-script#14410368 – Alohci Jul 21 '13 at 10:12
  • @Alohci: Good link. One of the large number of reasons why I prefer not to litter script tags all over the place, and certainly never nested within content (other than just before the closing `

    ` tag). I know that's what some people like to do, including some people you pretty much have to respect (Google Closure Library engineers, for instance), but it leads to that kind of thing...

    – T.J. Crowder Jul 21 '13 at 10:19
2

Yes, you can do this. Browsers are required to ignore attributes they don't recognize in any tag (to allow for graceful degradation when a document uses new features with an old browser). However, it would be better to use a dataset tag, since these are explicitly reserved for users, so they don't conflict with future HTML changes.

<script id="myscript" type="text/javascript" data-mycustomattribute="foo">

You can then access this either using an ordinary attribute accessor:

document.getElementById("myscript").getAttribute("mycustomattribute")

or with the dataset API:

document.getElementById("myscript").dataset.mycustomattribute

(but see the browser compatibility table in the documentation).

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You should be able to get it using jquery

$("script").attr("mycustomattribute");

Or try this using regular JavaScript

document.getElementsByTagName("script")[0].getAttribute("mycustomattribute");

Might bake sense to give a script tag an id to be able to do this

document.getElementById("someId").getAttribute("mycustomattribute");
TGH
  • 38,769
  • 12
  • 102
  • 135
  • 2
    Yes, true, but this is going to be a script block embedded on external sites where there is no guarantee of jquery existing. :( – tonejac Jul 21 '13 at 06:29
  • 1
    That's a workable solution as well. Thanks for the additional approach! – tonejac Jul 21 '13 at 06:48
0

I built a library for this very instance and it's quite easy to use:

<script id="your-library" src="./your-library.js" data-car="pagani" data-star-repo="yes, please :)">

and then you can get that data:

/**
 * This returns the following:
 *
 * {
 *   car: 'pagani',
 *   starRepo: 'yes, please :)'
 * }
 */

 ScriptTagData.getData('your-library');


 /**
  * This returns the juust <script> tag
  */

 ScriptTagData.getData('your-library');

You can download it via Bower, CDN or just take the code: https://github.com/FarhadG/script-tag-data

Vendetta
  • 63
  • 1
  • 8
  • Please do review [How to offer personal open-source libraries?](https://meta.stackexchange.com/q/229085) before posting your library to more questions. – Martijn Pieters Nov 23 '15 at 09:53