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

5
  • 1
    Is date and time necessary? I have a similar solution but using version number as apposed to date and time Commented Nov 27, 2018 at 11:42
  • Can you please show me it the variable should be dynamic and should not match with the previous variable value once script or stylesheet is loaded. Commented Nov 27, 2018 at 11:47
  • Ah i see. My version works well for production use for every time i push code. Not on a reload basis. Commented Nov 27, 2018 at 11:48
  • do you need this for your production version to prevent caching in new versions of your website or just for development? if you specify for what purpose you want this I can help you. Commented Nov 30, 2018 at 8:52
  • @molikh, I am wondering, the above tag resides in index.html and does it matter if this index.html is for production or development. If you can help me in either, this may solve my problem Commented Nov 30, 2018 at 9:19

9 Answers 9

10

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>

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, Can you please some similar solution for script as well. I have 7 script loading in head tag and the two scripts I need similar as stylesheet.
Please check my update. By the way, it seems you need to use the search before asking such basic questions.
<script> var link = document.createElement('script'); link.type= 'text/javascript'; link.src= '/assets/cder.js?v=' + Date.now(); document.body.appendChild(link); </script> <script> var link1 = document.createElement('script'); link1.type= 'text/javascript'; link1.src= '/assets/abc.js?v=' + Date.now(); document.body.appendChild(link1); </script>
Maybe, this is a basic question.But, I am not aware of it. This above solution in comment of mine is not working, if I am trying for my two scripts. Can you please suggest what I am doing wrong.
<script type="text/javascript"> var scripts = [ '/assets/abc.js', '/assets/def.js', ]; for (var i = 0; i < scripts.length; i++) { var script = document.createElement('script'); script.src = scripts[i] + '?v=' + Date.now(); document.body.appendChild(script); } </script> is not working nor showing on Network tab
|
3
+25

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

3 Comments

I have tried this but script is not being loaded on network tab.
I think that this will help you but the best approach for me is to do all these from backend if it is possible. Javascript runs in the browser so the user has to wait for all these calculations and requests to finish to get the proper view of the dom. I am not sure if the user experience would be the same if a script or a css file come after the page load. stackoverflow.com/questions/20821720/…
1

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.

Comments

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

2 Comments

Its not working, The scripts are not showing on network tab.
Kinda wierd, have you tried to put ur script on header and see if its actully loading? becouse that wierd what your saying.
0

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(...){}

Comments

0

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.

1 Comment

Sorry, it was a typo. Updated question. It does not help
0

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

Comments

0

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.

1 Comment

Hi, please give a example for better understanding
0

I tried using above some examples, but the performance was impacting, as the js file will load every-time the user logs in.

The below approach will make sure the js loads only when you give a new build.

Step 1: Add an hidden/(non hidden) element as below in your master layout page, this will contain your latest build number.

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.