gpt4 book ai didi

javascript - 仅在不存在时将脚本添加到头部

转载 作者:可可西里 更新时间:2023-11-01 01:40:53 24 4
gpt4 key购买 nike

我想在加载特定 div 时向我的站点添加其他脚本和样式。我首先定义脚本或样式表的路径,然后创建一个元素。此后,我将该元素 append 到 HTML 中的 head 标记。

但我想要一种方法来查看脚本或样式表是否已经在我再次追加之前被追加。 append 一个已经存在的脚本或样式表是愚蠢的。

问:如何使用javascript判断head标签中是否已经存在脚本,如果不存在则追加元素?

编辑

我根据@KernelPanik 的回答做了一个函数。它还没有工作,但希望它会。目前有问题的功能:my script appending function doesn't work

最佳答案

如果你会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);
}

在你的代码中写

appendScript('/Scripts/myScript.js');
appendStyle('/Content/myStyle.css');

关于javascript - 仅在不存在时将脚本添加到头部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15987668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com