简体   繁体   English

将类放在脚本标签上有好处吗?

[英]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并且很好奇将其写入代码是否有好处

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. 结果是屏幕上出现红色块,并且在Chrome中运行时脚本标记的内容可见。 IE does not render the script content visibly at all. IE根本不会显示脚本内容。 So <script> can be treated like any other tag, at least in Chrome. 因此, <script>可以像任何其他标记一样对待,至少在Chrome中是这样。 I'd argue that's an oversight on Chrome's part. 我认为这是对Chrome的疏忽。 This is Chrome 10.0.648.204 on 32bit Windows 7. 这是32位Windows 7上的Chrome 10.0.648.204。

渲染上面的html的效果

EDIT: Firefox 4 also renders the same thing. 编辑:Firefox 4也呈现相同的东西。

EDIT2: Possible use case? EDIT2:可能的用例? Use it as a "show source" for script on your page to show people how it works, perhaps on a blog about JavaScript? 使用它作为页面上脚本的“显示源”,向人们展示它是如何工作的,也许是在关于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>

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. 可以使用的地方是从许多脚本片段中动态选择一个以在其他地方使用,例如使用javascript模板语言。

Contrived Handlebars example: Contrived Handlebars示例:

<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));

According to w3c Standard, as described by w3schools.com a script tag does indeed support Global Attributes , one of which is the 'class' attribute. 根据w3c标准,如w3schools.com所述, 脚本标记确实支持全局属性 ,其中一个属于“类”属性。 Thus it is perfectly "legal" to have script tags with a specific class attribute, and browsers that break this are not fully w3c compliant. 因此,拥有具有特定类属性的脚本标记是完全“合法的”,并且打破此问题的浏览器不完全符合w3c。 The Global Attribute 'id' is also supported by the script tag. 脚本标记也支持全局属性“id”。

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. 至于使脚本标签具有'class'或'id'的可能效用,需要一个非常具体的用例,在发送它以由客户端浏览器呈现之前遍历w3c文档或DOM抽象,处理。 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. 在这种情况下,可以使用css样式选择来完成对文档进行更改的方法,并且对于分组脚本具有“id”和“class”可能由于许多不同的原因而有用。

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. 它可能并不是所有浏览器都支持,但浏览器(甚至是现代浏览器)以不同的方式解释w3c标准并以自己的方式实现其标准版本支持的情况并不少见。

我能想到的有一个脚本的class属性的唯一好处是jQuery可以选择元素并进行一些操作,例如复制它。

我可以想到的唯一一个有用的实例是脚本标签被动态添加到页面(彗星功能),因为这是您实际可能与脚本标签交互的少数几次之一。

It is useful when using the script tag itself as a reference for adjacent selectors. 当使用脚本标记本身作为相邻选择器的参考时,它很有用。

ie

 .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. 该脚本正在将一个元素(在本例中为iframe)直接写入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. 我不希望它立即显示,所以我使用脚本类来选择相邻的iframe以在页面加载时隐藏它。

Controlling the actual script tag display might not be itself useful, but used in combination with adjacent selectors, it does merit its uses. 控制实际的脚本标签显示本身可能不是很有用,但与相邻的选择器结合使用,它确实值得使用。

You can probably use class or id to erase your script written inside it for security reason like. 出于安全原因,您可以使用class或id来擦除写在其中的脚本。

<script id="erasable" type="text/javascript">
    //your code goes here
    document.getElementById('erasable').innerHTML = "";
</script>

Possible case: 可能的情况:

When you want to put a .png on top of a script using css. 当你想使用css将.png放在脚本之上时。 With z-index. 使用z-index。

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. 添加类或ID允许您使用Javascript选择脚本标记,然后获取其内容,例如JSON对象或任何内容。 This way you avoid creating a global variable (using jQuery here) : 这样你就可以避免创建一个全局变量(在这里使用jQuery):

<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 ): Javascript模板引擎也使用这种技术,例如( 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? 有关此问题的更多内容: 是否有在HTML中嵌入JSON的标准?

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, 我发现在脚本标记中添加了一个类,可用于开发代码编辑器,允许在页面上的特定块中编辑javascript,

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

我想到的一个直接好处是,Javascript / Jquery / etc现在可以通过类名选择该脚本元素。

I don't see any benefit since: 从那以后我没有看到任何好处:

  • Selecting it through CSS doesn't shouldn't do anything (visually) 通过CSS选择它 应该做任何事情(视觉上)
  • 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). 通过JS选择它是没有用的,因为复制,删除等没有做任何事情(因为JS内部只加载一次 - 任何更改后的字都被丢弃)。

I think it is not exactly correct to use the class attribute. 我认为使用class属性并不完全正确。 According to w3schools the script-tag does not support Standard Attributes to which the class property belongs. 根据w3schools ,script-tag不支持class属性所属的标准属性。 So jQuery might select it when using filtering for the class but you have no guarantee. 所以jQuery可能会在为类使用过滤时选择它,但你无法保证。 Also it's not sure if the behaviour is the same in all browsers. 此外,它不确定所有浏览器中的行为是否相同。

Ancient thread, but I'd like to add that today, in 2021, no more "only jQuery", since we live in Cloudflare workers world.古老的线程,但我想在今天补充一点,在 2021 年,不再“仅使用 jQuery”,因为我们生活在 Cloudflare 工人世界中。 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.例如,要在文件更新并且您使用 Cloudflare 缓存完整 HTML 时更新缓存破坏 (CB) 查询,您需要使用 CF 工作线程脚本更新 CB 查询。

<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.一个班级统治他们,一个班级找到他们,一个班级把他们全部带走,并在 Cloudflare 中绑定他们。 (FROM 'Lord of the Rings' WHERE CLASS = RING... ;) (来自“指环王”,其中 CLASS = RING...;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM