17

I came across this code

<script class="example" type="text/javascript">

and was curious if there is a benefit to writing that into your code

Simon MᶜKenzie
  • 8,344
  • 13
  • 50
  • 77
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321
  • I think you may be missing some code... :) – adamjford Mar 31 '11 at 21:33
  • 2
    A benefit to what? I don't understand what you're asking. – lonesomeday Mar 31 '11 at 21:34
  • actually no this is my question...i had the title wrong – Matt Elhotiby Mar 31 '11 at 21:34
  • I was not finished typing...the benefit of a class selector on a script tag – Matt Elhotiby Mar 31 '11 at 21:34
  • 9
    It has the benefit of invalidating the HTML, as `class` is not allowed on `script`, on HTML4, XHTML and HTML5. Not that anybody cares nowadays. – Wrikken Mar 31 '11 at 21:40
  • @Wrikken - reference please – Ken Liu Dec 05 '13 at 15:23
  • 1
    @KenLiu: I suppose you could find them yourself: [here is a XHTML dtd, and the defaults `%attrs` (which include 'class') are not found on the `script` element](http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-strict.dtd). However, `HTML5` is a moving target, and it's allowed in that version now. You can play around with http://validator.w3.org/: `` fails in HTML4 or XHTML, but now is allowed in HTML5. – Wrikken Dec 05 '13 at 16:19
  • 2
    Yes, it's allowed in HTML5: http://dev.w3.org/html5/markup/global-attributes.html#common.attrs.class http://dev.w3.org/html5/markup/script.html#script – Ken Liu Dec 05 '13 at 16:30
  • Yep, it is now, it wasn't in March 2011 (the draft you are linking to is from October 2012, 1.5 year later). – Wrikken Dec 05 '13 at 16:43
  • https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script – Cypher Apr 17 '14 at 15:49

14 Answers14

9

Visual styling's probably not a great case for this. Somewhere it could be used is dynamically selecting one from many script snippets to use elsewhere, for instance with with a javascript templating language.

Contrived Handlebars example:

<script class="greeting english" type="text/x-handlebars-template">
    <p>Hello {{name}}</p>
</script>
<script class="greeting spanish" type="text/x-handlebars-template">
    <p>Hola {{name}}</p>
</script>

...

var greeting_template = Handlebars.compile($('script.greeting.' + language).html()); 
$('#header').append(greeting_template(user));
Parker
  • 7,949
  • 5
  • 26
  • 21
9

I just ran a quick test with this markup:

<!DOCTYPE html>
<html>
<head>
    <style>
        .foo {
            display: block;
            border: 2px solid red;
            width: 10px;
            height: 10px;
        }
    </style>
</head>
<body>
    <script class="foo" type="text/javascript">
        alert("can you see me?");
    </script>
    after the script  
</body>
</html>

The result was a red block on the screen and the contents of the script tag visible when ran in Chrome. IE does not render the script content visibly at all. So <script> can be treated like any other tag, at least in Chrome. I'd argue that's an oversight on Chrome's part. This is Chrome 10.0.648.204 on 32bit Windows 7.

effect of rendering the above html

EDIT: Firefox 4 also renders the same thing.

EDIT2: Possible use case? Use it as a "show source" for script on your page to show people how it works, perhaps on a blog about JavaScript?

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
</head>
<body>
    <script class="foo" type="text/javascript">
        function foobar() {
            var a = 1;
        }   
    </script>
    after the script
    <a href="#">show me the script</a>

    <script type="text/javascript">
        $('a').click(function(event) {
            event.preventDefault();
            $("<div>").html($(".foo").text()).appendTo($("body"));
        });
    </script>
</body>
</html>
Matt Greer
  • 60,826
  • 17
  • 123
  • 123
6

According to w3c Standard, as described by w3schools.com a script tag does indeed support Global Attributes, one of which is the 'class' attribute. Thus it is perfectly "legal" to have script tags with a specific class attribute, and browsers that break this are not fully w3c compliant. The Global Attribute 'id' is also supported by the script tag.

As for the possible utility of having script tags with a 'class' or 'id' there would need to be a very specific usecase for which traversing a w3c document or a DOM abstraction, before sending it to be rendered by a client browser, is handled. In this case the means of making changes to a document could be done using css style selection and having 'id' and 'class' for grouping scripts could be useful for a number of different reasons.

It is a narrow and specific case, but one that I am actually involved in at this very moment. To say there is no usefulness to it is narrow minded and to say it is illegal by the standards is false. It may not be supported on all browsers, but it is not uncommon for browsers, even modern ones, to interpret the w3c standard differently and implement their version of standards support in their own way.

mcdonasm
  • 173
  • 3
  • 8
4

The only instance I can think of when this would be useful is when script tags are dynamically added to a page (comet functionality), as that is one of the few times when you might actually interact with a script tag.

jdc0589
  • 6,972
  • 5
  • 36
  • 39
3

The only benefit I can think of for having a class property for a script is that jQuery may be able to select the element and do some manipulation, for example duplicate it.

Jacob
  • 77,566
  • 24
  • 149
  • 228
2

It is useful when using the script tag itself as a reference for adjacent selectors.

i.e.

.example + iframe {height: none;}
<script class="example" type="text/javascript" src="//weird-addon.js">
</script>

In the above example, I am loading a script onto the page. The script is writing an element, in this case an iframe, directly to the DOM.

I don't want it to be shown immediately, so I am using the script class to select the adjacent iframe to hide it on page load.

Controlling the actual script tag display might not be itself useful, but used in combination with adjacent selectors, it does merit its uses.

inkovic
  • 315
  • 2
  • 12
1

You can probably use class or id to erase your script written inside it for security reason like.

<script id="erasable" type="text/javascript">
    //your code goes here
    document.getElementById('erasable').innerHTML = "";
</script>
Zeeshan Cornelius
  • 308
  • 1
  • 4
  • 15
0

Possible case:

When you want to put a .png on top of a script using css. With z-index.

San
  • 1
0

Adding a class or an ID let you select the script tag with Javascript, and then get its content, for example a JSON object, or anything. This way you avoid creating a global variable (using jQuery here) :

<script id="datas" type="text/javascript">
    {"id": 1}
</script>

<script type="text/javascript">
    // This part of the code should be in a JS module
    // To avoid creating a global "object" variable
    var object = JSON.parse($('#datas').html());
    console.log(object.id); // Log "1"
</script>

Javascript templating engines use this technique too, for example (Handlebars):

<script id="entry-template" type="text/x-handlebars-template">
    <div class="entry">
      <h1>{{title}}</h1>
      <div class="body">
        {{{body}}}
      </div>
    </div>
</script>

More to read on this question : Is there a standard for embedding JSON in HTML?

Community
  • 1
  • 1
Nico Prat
  • 686
  • 2
  • 6
  • 13
0

I have found adding a class to a script tag useful in developing a code editor that allows editing the javascript in specific blocks on a page,

<div id="idForABlock">
<script class="jsCustomJavascript">
//user generated code
</script>
</div>
0

A immediate benefit that comes to my mind is that Javascript/Jquery/etc can now select that script element by the class name.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
  • Indeed. But what could you then usefully do with the element once you'd selected it? – lonesomeday Mar 31 '11 at 21:38
  • @lonesomeday: Templating for example, or cleaning the page if you go full ajax – Micaël Félix Aug 19 '13 at 06:21
  • @MykaEyl `type="text/javascript"` means that it can't be a template. But generally, yes, you're right, if you don't care about a valid document. – lonesomeday Aug 19 '13 at 10:22
  • @lonesomeday I agree with you. I have to say that I do not like adding class names to scripts tags and I add a custom 'data-something="scriptid"' attribute instead (it can be selected with jQuery as well). – Micaël Félix Aug 20 '13 at 07:16
  • 2
    You could remove the ` – ericsoco Jan 22 '15 at 21:45
0

I don't see any benefit since:

  • Selecting it through CSS doesn't shouldn't do anything (visually)
  • Selecting it through JS isn't useful since duplicating, deleting etc, doesn't do a thing (since the JS inside is only loaded once - any changes afterwords are discarded).
Christian
  • 27,509
  • 17
  • 111
  • 155
  • Well at least if you select it from JS you can remove the script tag itself from the page to clean it up, plus templating. – Micaël Félix Aug 19 '13 at 06:23
  • I'm not sure what you mean by "cleanup" and even less by "templating". If you want to add JS to the page, there are plenty of ways without using a script tag (eg; `eval()`). – Christian Aug 19 '13 at 15:34
  • If you heavily use ajax, and every ajax get appended to the page, you'll end up with many scripts tags being added, and some of them will probably only be run once. So since anyway it's already been executed, to not see them in the source of the page you can remove them (they're not useful anyway). Eval is a bad suggestion. Plus using ajax you often have html and scripts. – Micaël Félix Aug 20 '13 at 07:09
  • And for "templating", search for jquery templating on the web you'll see what I mean. Templates are usually contained within script tags. – Micaël Félix Aug 20 '13 at 07:11
  • Uh, AJAX is never appended to the page... and even if it were, one should ideally change the `src` of an existing script rather than create a new one (it better for performance anyway). Regarding templating, I see what you mean, and frankly I think it's a bad hack. This feature we're discussing simply adds one more level of bad coding. – Christian Aug 20 '13 at 18:01
  • I can see my scripts text appended into the HTML (view source or inspect page on chrome), so they are (and it works). Why templating would be a bad hack? – Micaël Félix Aug 21 '13 at 07:03
0

I think it is not exactly correct to use the class attribute. According to w3schools the script-tag does not support Standard Attributes to which the class property belongs. So jQuery might select it when using filtering for the class but you have no guarantee. Also it's not sure if the behaviour is the same in all browsers.

Kuepper
  • 992
  • 13
  • 39
0

Ancient thread, but I'd like to add that today, in 2021, no more "only jQuery", since we live in Cloudflare workers world. So naming a script element does help to target them. For example, to update cache busting (CB) query when a file is updated and you're caching full HTML with Cloudflare, you need to update the CB query with CF workers script.

<script class="xyz-cb-query xyz-cb-vendor-js" src="/assets/vendor.js?v=938750039">    
<script class="xyz-cb-query xyz-cb-app-js" src="/assets/app.js?v=938750039">

One CLASS to rule them all, one CLASS to find them, One CLASS to bring them all, and in the Cloudflare bind them. (FROM 'Lord of the Rings' WHERE CLASS = RING... ;)

Nookeen
  • 445
  • 4
  • 7