[英]Append Dynamic version(variable ) in Script tag and stylesheet based on time
<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>
or,或者,
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>
I have tried this as below but the script is not loading on network tab.
我已尝试如下操作,但
script is not loading on network tab.
<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>
I am trying to add dynamic version(variable ) in script tag and stylesheet based on current time or some dynamic variable?我正在尝试根据当前时间或某个动态变量在脚本标记和样式表中添加动态版本(变量)?
If possible, Please help me with the shortest and efficient solution.如果可能,请帮助我提供最短且有效的解决方案。
How to achieve that?如何做到这一点?
If you are looking for the shortest solution, how about this?如果您正在寻找最短的解决方案,这个怎么样?
<script>document.write('<link href="/assets/cder.css?v=' + Date.now() + '" rel="stylesheet" />');</script>
A worthy alternative should be:一个有价值的替代方案应该是:
<script>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = '/assets/cder.css?v=' + Date.now();
document.body.appendChild(link);
</script>
Well, you must escape the closing script tag as follows:好吧,您必须按如下方式转义结束脚本标记:
<script>document.write('<script src="/assets/abc.js?v=' + Date.now() + '"><\/script>');</script>
An example of how to add several scripts:如何添加多个脚本的示例:
<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>
You could do this dynamically from javascript.您可以从 javascript 动态执行此操作。
<script>
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src', '/assets/abc.js?v='+new Date.getTime()); //was missing single quote
document.head.appendChild(my_awesome_script);
</script>
taken from Stack overflow answer取自堆栈溢出答案
It seems that you are confused with html
& javascript
.您似乎对
html
& javascript
感到困惑。
It's impossible to use html
which is mixed up with javascript
to archive something.不可能使用与
javascript
混合的html
来存档某些内容。
With SSR(Server Side Render)
使用
SSR(Server Side Render)
Using such as Handlebars
or another template engine.使用诸如
Handlebars
或其他模板引擎。
The timestamp
(as well as your version tag) should be rendered in server side before html was generated. timestamp
(以及您的版本标签)应该在生成 html 之前在服务器端呈现。
<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>
Without SSR(Server Side Render)
无
SSR(Server Side Render)
We can archive with javascript
after html
is returned by HTTP
request.我们可以在
HTTP
请求返回html
后使用javascript
进行存档。
let script = document.createElement('script');
script.setAttribute('src', `somefile?v=${Date.now()}`);
document.head.appendChild(script);
It's better to wrap a function to do this job.最好包装一个函数来完成这项工作。
<script [src]="'/assets/abc.js?v='+new Date.getTime();" type="text/javascript"></script>
if its not working try to create model and do it like this:如果它不起作用尝试创建模型并这样做:
this.someModel = "/assets/abc.js?v='"+new Date.getTime();
<script [src]="script" type="text/javascript"></script>
there are also more ways to do it.还有更多方法可以做到。
const time = new Date(2018, 10, 24, 22); // you can provide minutes and seconds if you want const today = new Date(); const head = document.querySelector('html head'); const body = document.querySelector('html body'); const styleFile = '<link href="/assets/cder.css?v=' + today.getTime() + '" rel="stylesheet"></link>'; const scriptFile = '<script src="/assets/abc.js?v=' + today.getTime() + '" type="text/javascript"></script>'; setInterval(() => { if ((time.getDate() === today.getDate()) && (time.getMonth() === today.getMonth()) && (time.getFullYear() === today.getFullYear()) && (time.getHours() === today.getHours())) { head.append(styleFile); body.append(scriptFile); } }, 60000);
<html> <head> <!-- here we will append style file --> </head> <body> <div>some dummy text</div> <!-- here we will append script file --> </body> </html>
why setInterval
?为什么设置
setInterval
? that how we tell the browser "please check every minute if the condition true" if it's, so append
new styleFile and scriptFile .我们如何告诉浏览器“如果条件为真,请每分钟检查一次”,如果条件成立,因此
append
新的styleFile和scriptFile 。
Note: you can provide minutes
and seconds
in time as well if you want but remember to also add the appropriate condition in if(...){}
注意:如果需要,您也可以提供
minutes
和seconds
,但请记住还要在if(...){}
添加适当的条件
From all the testing I have done it seems that the final attempt that you tried works flawlessly when using [0] instead of [6] or any other value for that matter.从我所做的所有测试来看,当使用 [0] 而不是 [6] 或任何其他值时,您尝试的最后一次尝试似乎完美无缺。 Also why do you have multiple head tags?
另外为什么你有多个头部标签? was this a typo and you meant header?
这是一个错字吗,你的意思是标题? it seems to work with any number of headers.
它似乎适用于任意数量的标题。
But really this type of thing should be handled via backend if possible.但实际上,如果可能的话,这种类型的事情应该通过后端处理。
While other answers here correctly describe how to do this in a script, I want to note three things:虽然此处的其他答案正确地描述了如何在脚本中执行此操作,但我想注意三件事:
async
attribute on any run-time <script>
element, otherwise it degrades performance, sometimes significantly.<script>
元素上设置async
属性,否则会降低性能,有时会显着降低。 Search engines penalize this heavily. ``` ``
``` ``
But note that appending a script tag regardless of using the async
attribute will block rendering.但请注意,无论是否使用
async
属性,附加脚本标记都会阻止渲染。 Read this for more details . 阅读本文了解更多详情。
Your script is not loading because its not new Date.getTime()
but new Date().getTime()
or just use Date.now()
.您的脚本没有加载,因为它不是
new Date.getTime()
而是new Date().getTime()
或者只是使用Date.now()
。 Additionally To prevent browser cache you can add no-cache header for example using .htaccess
此外,为了防止浏览器缓存,您可以添加 no-cache 标头,例如使用
.htaccess
<filesMatch "\.(js|css)">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</filesMatch>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/javascript "access plus 1 seconds"
ExpiresByType text/css "access plus 1 seconds"
</IfModule>
and for javascript function和 javascript 函数
function appendJS(url) {
var s = document.createElement('script');
s.src = url + '?v=' + Date.now();
document.body.appendChild(s);
}
function appendCSS(url) {
var s = document.createElement('link');
s.rel = 'stylesheet';
s.href = url + '?v=' + Date.now();
document.body.appendChild(s);
}
appendJS('/assets/abc.js');
appendCSS('/assets/cder.css');
I tried using above some examples, but the performance was impacting, as the js file will load every-time the user logs in.我尝试使用上面的一些示例,但性能受到影响,因为每次用户登录时都会加载 js 文件。
The below approach will make sure the js loads only when you give a new build.以下方法将确保仅在您提供新构建时加载 js。
Step 1: Add an hidden/(non hidden) element as below in your master layout page, this will contain your latest build number.第 1 步:在您的主布局页面中添加如下隐藏/(非隐藏)元素,这将包含您的最新版本号。
<p id="BuildNumber">Build Number : @System.Diagnostics.FileVersionInfo.GetVersionInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", "<yourDllName>.dll")).FileVersion
</p>
Step 2 : Use below script tag to version your js files, please update the script type as per your usage.第 2 步:使用下面的脚本标签来版本化您的 js 文件,请根据您的使用情况更新脚本类型。
<script>
var script = document.createElement('script');
script.setAttribute('src', '/Scripts/Common/<fileName>.min.js?v=' + document.querySelector('#BuildNumber').innerHTML.split(': ')[1]);
script.type = 'text/babel';
document.head.appendChild(script);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.