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 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?

Answers:

Answer

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>

Answer

You could do this dynamically from 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

Answer
<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.

Answer

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? that how we tell the browser "please check every minute if the condition true" if it's, so append new styleFile and 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(...){}

Answer

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. 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.

Answer

It seems that you are confused with html & javascript.

It's impossible to use html which is mixed up with javascript to archive something.


With SSR(Server Side Render)

Using such as Handlebars or another template engine.

The timestamp(as well as your version tag) should be rendered in server side before html was generated.

<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)

We can archive with javascript after html is returned by HTTP request.

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.

Answer

Your script is not loading because its not new Date.getTime() but new Date().getTime() or just use Date.now(). Additionally To prevent browser cache you can add no-cache header for example using .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

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');
Answer

While other answers here correctly describe how to do this in a script, I want to note three things:

  1. You should do this at build-time using hashes, not timestamps, otherwise, every time the date changes your cache could be cleared. That's not a great user experience. Be intentional about when and why you're fetching this. Webpack has a nifty build plugin for creating hashes in file names.
  2. Use headers to drive whether a new file should be fetched.
  3. Make sure you're setting the async attribute on any run-time <script> element, otherwise it degrades performance, sometimes significantly. Search engines penalize this heavily.

```

```

But note that appending a script tag regardless of using the async attribute will block rendering. Read this for more details.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.