Search code examples
javascriptangularangular7

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?


Solution

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