gpt4 book ai didi

javascript - 根据时间在脚本标签和样式表中附加动态版本(变量)

转载 作者:太空狗 更新时间:2023-10-29 17:53:14 24 4
gpt4 key购买 nike

<script src="/assets/abc.js?v='+new Date.getTime();" type="text/javascript"></script>

<link href="/assets/cder.css?v='+new Date.getTime();" rel="stylesheet"></link>

或者,

var myVariable = Math.floor(Math.random() * 999999999999);
<script src="/assets/abc.js?v='+myVariable ;" type="text/javascript"></script>

<link href="/assets/cder.css?v='+new Date.getTime();" rel="stylesheet"></link>

我已尝试如下所示,但脚本未加载到网络选项卡上。

<script type="text/javascript>
var script = document.createElement('script');
script.setAttribute('src', '/assets/abc.js?v=' + new Date.getTime());
var head1 = document.getElementsByTagName("head")[0];
head1.appendChild(script);
</script>

我正在尝试根据当前时间或某些动态变量在脚本标记和样式表中添加动态版本(变量)?

如果可能,请帮助我找到最短且高效的解决方案。

如何实现?

最佳答案

如果您正在寻找最短的解决方案,这个怎么样?

<script>document.write('<link href="/assets/cder.css?v=' + Date.now() + '" rel="stylesheet" />');</script>

一个有值(value)的选择应该是:

<script>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/assets/cder.css?v=' + Date.now();
document.body.appendChild(link);
</script>

那么,您必须按如下方式转义结束脚本标记:

<script>document.write('<script src="/assets/abc.js?v=' + Date.now() + '"><\/script>');</script>

如何添加多个脚本的示例:

<script>
var scripts = [
'/assets/abc.js',
'/assets/def.js',
];

for (var i = 0; i < scripts.length; i++) {
var script = document.createElement('script');
script.onerror = function() {
alert('Could not load ' + this.src);
};

script.src = scripts[i] + '?v=' + Date.now();
document.body.appendChild(script);
}
</script>

关于javascript - 根据时间在脚本标签和样式表中附加动态版本(变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53436768/

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