Forum Moderators: open

Message Too Old, No Replies

How Do I call A JS Script Randomly based on page reload?

         

RegGFX

4:56 pm on Dec 29, 2006 (gmt 0)

10+ Year Member



How Do I call A JS Script Randomly based on page reload?

Now Here’s a challenge…

I have a situation where I have 2 or 3 different js scripts and I need to call them randomly.
In other words a different js script such as


<script type="text/javascript" src="option1.js"> </script>
or
<script type="text/javascript" src="option2.js"> </script>
or
<script type="text/javascript" src="option3.js"> </script>

Will randomly load when ever user visits the page or refreshes the page.
This basically will work the same way as if you were to randlomly load images based on page refresh, except the script I am looking for will load js script instead of images.

Does anyone have any code examples on how I could accomplish this?
Thanks. Please Advise.

Fotiman

5:01 pm on Dec 29, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I don't think you can do this with JavaScript alone. You could have some server side processing (using PHP, ASP, ASP.NET, etc.) to randomly pick with script tag to output. Alternatively, if you can modify those 3 script files to all live in a single file and to be called by some function call, then you could use JavaScript to randomly choose which function to call.

mehh

3:13 pm on Dec 30, 2006 (gmt 0)

10+ Year Member



The Following should work. I only tested it in firefox though.

<html>
<head>
<title>
Random Script
</title>
<script type="text/javascript">
var srcs=new Array("option1.js","option3.js","option2.js","xyz.js")//Script sources
var randomScript
if(randomScript=document.createElement('script'))
{
randomScript.type="text/Javascript"
randomScript.src=srcs[(Math.floor(Math.random()*srcs.length))];
document.getElementsByTagName('head')[0].appendChild(randomScript);
}
</script>
</head>
<body>
hello
</body>
</html>

RegGFX

6:09 am on Jan 7, 2007 (gmt 0)

10+ Year Member



HEY THAT WORKED GREAT! FANTASTIC!

It works in I.E. as well

Thanks you SO MUCH! for the tip!

Very Much appreciated.