javascript 在脚本标签中使用 ID 属性有什么意义?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11960180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the point of using an ID attribute in a script tag?
提问by John
Basically what I am asking is what is the point of giving my script tags an id attribute? Can the routines inside of them be called or referenced differently because of this identification? Could this cause any problems making the script/page act funny?
基本上我要问的是给我的脚本标签一个 id 属性有什么意义?由于这种标识,它们内部的例程是否可以被不同地调用或引用?这会导致任何问题使脚本/页面变得有趣吗?
回答by Michael Berkowski
The id
is just another accessor of the <script>
tag inside the DOM tree. You could in theory use document.getElementById()
to retrieve the <script>
node and delete it or add other attributes (though I don't believe you can modify the src
attribute once it has loaded in the DOM). The id
isn't required for those operations though -- it could have been accessed by any DOM function such as getElementsByTagName("script")
as well.
这id
只是<script>
DOM 树中标签的另一个访问器。理论上,您可以使用document.getElementById()
来检索<script>
节点并删除它或添加其他属性(尽管我不相信src
一旦它加载到 DOM 中就可以修改该属性)。但是id
,这些操作不需要 - 它也可以被任何 DOM 函数访问getElementsByTagName("script")
。
If you do need to access the <script>
tag with DOM manipulations, the id
makes it just a little easier. Otherwise, there is little benefit1.
如果您确实需要<script>
使用 DOM 操作访问标记,这id
会使其更容易一些。否则,几乎没有好处1。
1That is sort of true of adding an id
attribute to anyDOM node, though nodes affecting presentation can also benefit from CSS targeting the id
, unlike a <script>
tag...
1将id
属性添加到任何DOM 节点都是如此,尽管影响表示的节点也可以从针对 的 CSS 中受益id
,这与<script>
标记不同...
回答by sv_in
As the earlier answers have mentioned, once the code in the script tag runs, it's results will not be undo-ed by replacing/deleting the script node.
正如前面的答案所提到的,一旦脚本标签中的代码运行,它的结果将不会通过替换/删除脚本节点来撤消。
But the id can be useful if the code has not run till now. Following is such a script tag:
但是如果代码直到现在还没有运行,id 会很有用。以下是这样一个脚本标签:
<script id="code1" type="text/myjs">.....</script>
Since the browser is not aware of this type of script, it will ignore it's execution but the tag and it's code will still be available in the DOM.
由于浏览器不知道这种类型的脚本,它会忽略它的执行,但标签和它的代码在 DOM 中仍然可用。
Working example: http://jsfiddle.net/sv_in/rt9Q2/
工作示例:http: //jsfiddle.net/sv_in/rt9Q2/
This is largely used for client side templates. A template, example for Mustache.js, is stored in such a script tag. When it is needed to be compiled, it is obtained from tag using it's id. Advantage with this approach is that the view (templates) and the model (js variable which contain data to be shown in the view) is completely separate.
这主要用于客户端模板。模板,例如Mustache.js,存储在这样的脚本标记中。当需要编译时,它是从标签中使用它的id获取的。这种方法的优点是视图(模板)和模型(包含要在视图中显示的数据的 js 变量)是完全分开的。
Other than this practise, there is no general purpose use for an id for a script tag
除了这种做法,脚本标签的 id 没有通用用途
回答by Taha Rehman Siddiqui
There is no meaning giving id to your script tags, the scripts on a page just execute in a sequence they are on the page.
给你的脚本标签赋予 id 没有意义,页面上的脚本只是按照它们在页面上的顺序执行。
回答by OmegaJunior
Adding an id attribute to your script elements serves 2 specific purposes:
1. you can recognise your scripts when reading the web page's source code;
2. the HTML reference says you should be able to overwrite the contents of an identifiable element (but experience teaches us that few browsers actually do that).
将 id 属性添加到您的脚本元素有两个特定目的:
1. 在阅读网页源代码时您可以识别您的脚本;
2. HTML 参考说你应该能够覆盖可识别元素的内容(但经验告诉我们,很少有浏览器真正做到这一点)。
For instance, if you already have a script with id="myParticularScript", then adding a new script element with that same id should replace the old one, loading any new (or the same) source you specified in the src attribute.
例如,如果您已经有一个 id="myParticularScript" 的脚本,那么添加一个具有相同 ID 的新脚本元素应该会替换旧的脚本元素,加载您在 src 属性中指定的任何新(或相同)源。
While my experience with dynamic loading of javascripts proves that the new script does get loaded into the browser, no browser I tested managed to replace the older element that holds the same id.
虽然我动态加载 javascripts 的经验证明新脚本确实加载到浏览器中,但我测试的浏览器没有设法替换具有相同 ID 的旧元素。
So that just leaves the first purpose: easy recognition. In my work, we use systems to generate web pages, and we didn't always know which script (or css link, for that matter) is added by which component. We solved this by adding ids to both the script tags and the css link tags - ids that we were able to recognise and trace back to our systems.
所以只剩下第一个目的:容易识别。在我的工作中,我们使用系统来生成网页,我们并不总是知道哪个脚本(或 css 链接,就此而言)是由哪个组件添加的。我们通过向脚本标签和 css 链接标签添加 id 来解决这个问题 - 我们能够识别并追溯到我们的系统的 id。
回答by GamaSharma
This might be useful for checking the existence of the resource file in the src url attribute in the server. For cache busting, reverencing the file name of .js and .css files are required. This will help in checking out if the file names has changed in the server and then do a reload via code via
这对于检查服务器中 src url 属性中资源文件的存在可能很有用。对于缓存破坏,需要尊重 .js 和 .css 文件的文件名。这将有助于检查服务器中的文件名是否已更改,然后通过代码重新加载
$window.location.reload()
Code example (angularjs):
代码示例(angularjs):
service.reloadApplication = function () {
var script = document.getElementsById("scriptAppMin");
if (!!script.getAttribute('src') && doesFileExist(script.getAttribute('src')) == false)
$window.location.reload();
}
function doesFileExist(fileUrl) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', fileUrl, false);
xhr.send();
return !(xhr.status == "404");
}
回答by niutech
回答by ADTC
I found a very novel use for giving ID to a script
tag. I had embedded tawk.toscript in my website to show its chat widget. The problem is, the widget does not hide when I want to print the page. So you would see the widget repeated on every page in the print preview, often obscuring the page contents!
我发现了一种为script
标签提供 ID 的非常新颖的用途。我在我的网站中嵌入了tawk.to脚本以显示其聊天小部件。问题是,当我想打印页面时,小部件不会隐藏。因此,您会在打印预览的每个页面上看到该小部件重复出现,通常会掩盖页面内容!
In order to resolve the problem, I first observed how the widget is added. I found out that the widget is added right after the script tag. But the widget (encased in a div
tag) does not have any class, and it has a randomly generated ID which is different each time.
为了解决这个问题,我首先观察了widget是如何添加的。我发现小部件是在脚本标签之后添加的。但是小部件(封装在div
标签中)没有任何类,它有一个随机生成的 ID,每次都不同。
There had to be another way to catch hold of that widget (the div
tag) without relying on JavaScript tricks. That's when I learnt that CSS has an "adjacent sibling"or "next sibling" selector, which surprisingly has very decent browser support.
必须有另一种方法来抓住那个小部件(div
标签)而不依赖于 JavaScript 技巧。那时我了解到 CSS 有一个“相邻兄弟”或“下一个兄弟”选择器,令人惊讶的是,它具有非常不错的浏览器支持。
So first, I gave an ID for the script tag.
所以首先,我为脚本标签提供了一个 ID。
<script type="text/javascript" id="tawk-to-script">
Then I used the IDand the next sibling selector to apply CSS to the widget.
然后我使用 ID和下一个兄弟选择器将 CSS 应用到小部件。
@media print {
script#tawk-to-script + div {
display: none !important;
}
}
Viola! Problem solved.
中提琴!问题解决了。
回答by DavChana
I used script
id
tag in a bookmarklet; I add the script
element via Javascript to DOM
alongwith a div
; then use it; & when/if user clicks the Close
button on my added div
; I find this script
element by ID & delete it from DOM to leave the page as I found it.
我script
id
在书签中使用了标签;我添加了script
通过JavaScript元素DOM
非常久远一个div
; 然后使用它;& 当/如果用户单击Close
我添加的按钮时div
;我script
通过 ID找到这个元素并从 DOM 中删除它以离开我找到的页面。
回答by r0u9hn3ck
They might come in handy when you think of loading scripts lazily. Also, I remember I once used an ID on a script tag to facilitate the changes on meta content, per state change (it was a single page application).
当您考虑延迟加载脚本时,它们可能会派上用场。另外,我记得我曾经在脚本标签上使用 ID 来促进元内容的更改,每个状态更改(它是一个单页面应用程序)。
With an ID on a script tag, you can check if on a particular instance, whether a script tag with a particular ID is there in the DOM or not. If it's not there, and if your route requires it to be there, you can load it then (given on certain conditions).
使用脚本标签上的 ID,您可以检查在特定实例上,DOM 中是否存在具有特定 ID 的脚本标签。如果它不存在,并且您的路线需要它在那里,那么您可以加载它(在某些条件下)。
Suppose there's a script that you need to load lazily. Let's take an example of some chat widget. Cases can arise that may tend you to load the chat widget only and only whenever a user happens to click on, say, a chat button.
假设有一个需要延迟加载的脚本。让我们举一个聊天小部件的例子。可能会出现这样的情况,您可能会倾向于仅加载聊天小部件,并且仅在用户碰巧点击聊天按钮时才加载。
Here, you'll be lazily loading the chat. So, a possible case out of it can be: "if user clicks on chat button, inject the chat widget js into the DOM".
在这里,您将懒惰地加载聊天。因此,可能的情况是:“如果用户单击聊天按钮,则将聊天小部件 js 注入 DOM”。
Simple? Hell yes. But, think about the case when a user clicks on the chat button again. What will happen? The same script would be injected again, but you certainly don't want that to happen, do you?
简单的?当然好。但是,想想用户再次点击聊天按钮的情况。会发生什么?将再次注入相同的脚本,但您肯定不希望这种情况发生,对吗?
So, let's say the chat widget js goes into the DOM by:
因此,假设聊天小部件 js 通过以下方式进入 DOM:
<script id="chatWidgetScript" src="...whatever..."></script>
A good solution to tackle the "second click" problem on the chat button will be to see if the script already exists in the DOM, and if it does, don't let the same get appended twice into the DOM.
解决聊天按钮上的“第二次点击”问题的一个很好的解决方案是查看脚本是否已经存在于 DOM 中,如果存在,不要让相同的脚本两次附加到 DOM 中。
So, your button could be:
所以,你的按钮可能是:
<button onclick="loadChatWidget()"> Chat! </button>
And your loadChatWidget() function could be:
你的 loadChatWidget() 函数可能是:
loadChatWidget(){
if(document.getElementById("chatWidgetScript")){
//chat script is already there in the DOM, no need to load it again.
return;
}
/*
if document.getElementById("chatWidgetScript") returns null, this would
mean that the chat widget isn't there in the DOM, and you might want to
load the same now.
*/
// LOAD SCRIPT HERE
}
This is just one way of using an ID on a script tag, and it is useful too!
这只是在脚本标签上使用 ID 的一种方式,它也很有用!