Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a benefit to putting a class on a script tag?

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

like image 974
Matt Elhotiby Avatar asked Mar 31 '11 21:03

Matt Elhotiby


1 Answers

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>
like image 59
Matt Greer Avatar answered Oct 09 '22 18:10

Matt Greer