javascript 如果不存在,则仅将脚本添加到头部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15987668/
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
only add script to head if doesn't exist
提问by Dimser
I want to add additional scripts and styles to my site when a specific div
is loaded.
I start out by defining a path to either a script or stylesheet and then create an element. Hereafter I append the element to the head tag in HTML.
我想在加载特定脚本时向我的站点添加其他脚本和样式div
。我首先定义脚本或样式表的路径,然后创建一个元素。此后,我将元素附加到 HTML 中的 head 标记。
But I would like a way to see if the script or stylesheet already has been append before I append it again. It would be stupid to append an already existing script or stylesheet.
但是我想要一种方法来查看脚本或样式表是否已经被追加,然后再追加。附加一个已经存在的脚本或样式表是愚蠢的。
Q: How do I use javascript to check wether or not a script already exists in the head tag, and then append the element if not?
问:如何使用javascript检查head标签中是否已经存在脚本,如果不存在则追加元素?
EDIT
编辑
I have made a function based on the answer from @KernelPanik. It doesn't work yet but hopefully it will. The function is currently in question: my script appending function doesn't work
我根据@KernelPanik 的回答做了一个函数。它还没有工作,但希望它会。该函数当前存在问题:我的脚本附加函数不起作用
回答by Bahram Boroumandan
If you can use jquery, this code is good
如果你可以使用jquery,这段代码就很好
function appendScript(filepath) {
if ($('head script[src="' + filepath + '"]').length > 0)
return;
var ele = document.createElement('script');
ele.setAttribute("type", "text/javascript");
ele.setAttribute("src", filepath);
$('head').append(ele);
}
function appendStyle(filepath) {
if ($('head link[href="' + filepath + '"]').length > 0)
return;
var ele = document.createElement('link');
ele.setAttribute("type", "text/css");
ele.setAttribute("rel", "Stylesheet");
ele.setAttribute("href", filepath);
$('head').append(ele);
}
In your code write
在你的代码中写
appendScript('/Scripts/myScript.js');
appendStyle('/Content/myStyle.css');
回答by Hyman Lee
var lib = '/public/js/lib.js';
if (!isLoadedScript(lib)) {
loadScript(lib);
}
// Detect if library loaded
function isLoadedScript(lib) {
return document.querySelectorAll('[src="' + lib + '"]').length > 0
}
// Load library
function loadScript(lib) {
var script = document.createElement('script');
script.setAttribute('src', lib);
document.getElementsByTagName('head')[0].appendChild(script);
return script;
}
回答by KernelPanik
You can use the DOM getElementsByTagName("script")
to get all of the <script>
tags in the document. Then you can check the src
urls of each script tag returned, for the url of the script(s) that you have added to the head section. Likewise, you can do something similar for the style sheets by replacing the search of "script" with "style".
您可以使用 DOMgetElementsByTagName("script")
来获取<script>
文档中的所有标签。然后,您可以检查src
返回的每个脚本标记的 url,以获取已添加到 head 部分的脚本的 url。同样,您可以通过将“脚本”的搜索替换为“样式”来对样式表执行类似的操作。
For example, if the url of the script appended to the <head>
section is header_url.html
例如,如果附加到该<head>
部分的脚本的 url是header_url.html
var x = document.getElementsByTagName("script");
var header_already_added = false;
for (var i=0; i< x.length; i++){
if (x[i].src == "header_url.html"){
// ... do not add header again
header_already_added = true;
}
}
if (header_already_added == false){
// add header if not already added
}
Likewise, if the url of the style appended to the <head>
section is header_style.css
同样,如果附加到该<head>
部分的样式的 url是header_style.css
var x = document.getElementsByTagName("style");
var header_already_added = false;
for (var i=0; i< x.length; i++){
if (x[i].src == "header_style.css"){
// ... do not add header again
header_already_added = true;
}
}
if (header_already_added == false){
// add header if not already added
}
A similar question was also asked here: Check if Javascript script exists on page
这里也有人问了一个类似的问题:Check if Javascript script exists on page
回答by Kristian Oubre
I used Hyman Lee's solution. It was easy to implement and quickly versitile with just about any type file.... I didn't expand on anything ...I actually probably stupefied it a bit... just wanted to list what I did in case it helps someone else...
我使用了 Hyman Lee 的解决方案。它很容易实现,并且几乎可以使用任何类型的文件快速通用......我没有扩展任何东西......我实际上可能有点傻......只是想列出我所做的以防万一它对某人有帮助别的...
var lib_jq = '//pathtofile/jquery.js';
var lib_bs = '//pathtofile/bootstrap.min.3.5.js';
var lib_cs = '//pathtofile.css';
///checks files with the SRC attribute
function isLoadedScript(lib) {
return document.querySelectorAll('[src="' + lib + '"]').length > 0
}
///checks files with the HREF attribute
function isLoadedCss(lib) {
return document.querySelectorAll('[href="' + lib + '"]').length > 0
}
///loads the script.js files
function loadScript(link) {
document.write('<scr' + 'ipt type="text/javascript" src="'+link+'"></scr' + 'ipt>');
}
///loads the style.css files
function loadCss(link) {
document.write('<link rel="stylesheet" href="'+link+'">');
}
/// run funtion; if no file is listed, then it runs the function to grab the URL listed. ///Run a seperate one for each file you wish to check.
if (!isLoadedScript(lib_jq)) { loadScript(lib_jq); }
if (!isLoadedScript(lib_bs)) { loadScript(lib_bs); }
if (!isLoadedCss(lib_cs)) { loadCss(lib_cs); }
I know there is always a "better" and more "elegant" solution, but for us beginiers, we got to get it working before we can start to understand it...
回答by Thomas Gratier
Another way with a function helper like below
使用如下函数助手的另一种方式
function isScriptAlreadyPresent(url) {
var scripts = Array.prototype.slice.call(document.scripts);
return scripts.some(function(el) {
return el.src && el.src != undefined && el.src == url;
});
}
isScriptAlreadyPresent('http://your_script_url.tld/your_lib.js');
It uses Array.prototype.somefunction. You may need a es5-shimif your are in browsers not supporting ES5 (IE7 and IE8...)
它使用Array.prototype.some函数。如果您使用的是不支持 ES5(IE7 和 IE8...)的浏览器,您可能需要一个es5-shim
回答by Fakefish
maybe headjscan help you.
也许headjs可以帮助你。
or maybe you can add onload attribute in the script tag.
或者您可以在脚本标签中添加 onload 属性。
my english is a little poor,so maybe i'm misunderstand your question.
我的英语有点差,所以也许我误解了你的问题。
if(ie){
js.onreadystatechange = function(){
if(js.readyState == 'complete'){
callback(js);
}
}
else{
js.onload = function(){
callback(js);
}
回答by BobG8
You can try calling some function, object, variable from that js script file, if it finds it then it exists, if not, you need to insert that js script file.
您可以尝试从该 js 脚本文件中调用一些函数、对象、变量,如果找到它,则它存在,如果没有,则需要插入该 js 脚本文件。