1

Hello I need help in assigning a random number to the src file in a script tag. I have read all the posts I could find, but not making any head way.

so here is what i am trying to do. In the code below, the file referenced by the src tag is myjsfile.1234.js.

What i want to is randomly generate the "1234" every time the page is loaded.

<script data-cfasync="false" id = "myid" src="https://www.example.com/myjsfile.1234.js" type="text/javascript">   </script> 

For example I have tried this without success

<script>
var randomnos = Math.ceil(Math.random() * 1000000000);
var mysource = "https://www.example.com/myjsfile."+randomnos+".js";
</script>
<script data-cfasync="false" id = "myid" src=mysource  type="text/javascript"></script>

So will appreciate any help I can get

Ehis Asibor
  • 37
  • 3
  • 11
  • You'll need to create the script tag programmatically and add it to the page. See, for example this link:http://stackoverflow.com/questions/13121948/dynamically-add-script-tag-with-src-that-may-include-document-write or http://stackoverflow.com/questions/610995/cant-append-script-element – Jacob Mattison Feb 23 '16 at 21:06

2 Answers2

2

Another way: using Jquery you can use $.getScript()

var randomnos = Math.ceil(Math.random() * 1000000000);
var mysource = "https://www.example.com/myjsfile."+randomnos+".js";

window.onload = function() {
   $.getScript(mysource,function(){console.log('loaded')})
}
Taran J
  • 805
  • 6
  • 10
1

You need to create script element programatically and append it to html page:

var randomnos = Math.ceil(Math.random() * 1000000000);
var mysource = "https://www.example.com/myjsfile."+randomnos+".js";

window.onload = function() {
    var script = document.createElement('script');
    script.src = mysource;
    document.head.appendChild(script);
}
madox2
  • 49,493
  • 17
  • 99
  • 99
  • If i do it this way, the called script is not executed... it just changes the tag and stops there. Obviously I want the contents of the new src file to be executed – Ehis Asibor Feb 23 '16 at 21:10
  • @EhisAsibor works for me. Try to do it with some known script, not with random one – madox2 Feb 23 '16 at 21:29