Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Run a Random Script

Status
Not open for further replies.

dcroe05

Programmer
Feb 15, 2005
44
US
Is there a way to randomly run a different script when a page is loaded?

I'm a VBA programmer, not javascript (but I'm learning). I have a script that randomly displays the name of one of the victims of 9/11. But as there are so many victims the script is 400K everytime the page loads. I'd like to reduce the bandwidth by breaking up the list into 50 randomization scripts, and upon page load, randomly run one of the scripts.

Is there a way to do this?
 
Sounds like it would be more efficient to do this as a server-side script. You could have an array with all the names and then select one at random to display.

However, there have been some discussion lately with dynamically including a .js file. You could probably take that idea to break your names array into smaller files and then load one of those randomly.

Let's do a little looking.

Einstein47
There are no kangaroos in Austria!
[[]Starbase47.com]
 
Ok - Looking deeper I found that there is a FAQ about using AJAX to get the .js file to avoid errors that can happen if the script tries to run and the file isn't there yet.


Basically this is what you want to do:
Code:
<script type="text/javascript">
window.onload=get_name;

function get_name() {
  [green]// First load one of the 50 array name lists (0-49)[/green]
  include("nameArray" + Math.round(Math.random() * 50));
  [green]// Next pick a name[/green]
  name = array[(Math.round(Math.random() * array.length))];
  [green]// Last display it on the page [/green]
  document.getElementById("nameDiv").innerHTML = name;
}

function include(src)
{
  var js=document.createElement('script');
  js.type='text/javascript';

  [green]// Attempt to create an AJAX object[/green]
  var xmlHttp;
  try{xmlHttp=new XMLHttpRequest();}
  catch(e){
    try{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}
    catch(e){
      try{xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}
      catch(e){
        [green]// Ajax not supported, use DOM instead.[/green]
        js.src=src;document.getElementsByTagName('head')[0].appendChild(js);
      }
    }
  }

  if(xmlHttp){
    xmlHttp.open("GET",src,false);
    xmlHttp.onreadystatechange=function(){
      if(xmlHttp.readyState==4){
        js.text = xmlHttp.responseText;
        document.getElementsByTagName('head')[0].appendChild(js);
      }
    }
    xmlHttp.send(null);
  }
}
</script>
...

<!-- Then somewhere in your HTML -->
<div id="nameDiv"></div>

And here is what each of your "nameArray#.js" files needs to look like:
Code:
var array = new Array(
 "Aaron Abraham",
 "John Doe",
 ... );
I'm sure someone will correct me - but I think that should work.

Einstein47
There are no kangaroos in Austria!
[&#91;]Starbase47.com]
 
Hi

Einstein47 said:
[tt][COLOR=red pink]var array = new Array([/color]
[COLOR=red pink] "[/color]Aaron Abraham[COLOR=red pink]",[/color]
[COLOR=red pink] "[/color]John Doe[COLOR=red pink]",[/color]
[COLOR=red pink] [/color]...[COLOR=red pink] );[/color][/tt]
If you are loading the list with [tt]XMLHttpRequest[/tt], then you can cut off what I marked with red. Just have the names in a plain text file, then [tt]split()[/tt] it to have the array.

According to Wikipedia, there should be 2974 names. At that amount you could try to front compress them to reduce storage space. And it is not too complicate to code.

Feherke.
 
Einstein47 & feherke,

Thank you for your replies.

Einstein, in between your first and second replies I used you mention of "dynamically including a .js" to search google and got a great result that showed me why the code I have alrady written wasn't working. There is a trick to call one .js from another by just using document.write and once I did that I could already use the .js files I had prepared with the names.

I am going to play with the code you gave me to try ti refine the whole thing into a less clunky script, but for now the reduced bandwidth is helping my site move faster.

Thanks,

dcroe05
 
[&nbsp;]
Here is some JS that I use with many pages to generate a random saying each time the page is refreshed. This particular one is very short and therefore embedded on the page. The ones with longer lists are in .js includes.

It sounds like a variation of this is what you are looking for for your pages.


function Writedefaultblurb(){
var text = new Array(1);
text[0] = 5;
text[1] = "A liberal is someone who has the PERCEPTION that he can get something for nothing - A conservative is someone who faces the REALITY that everything has a cost.";
text[2] = "If you think health care is expensive now, wait until you see what it costs when it's free. - <I>P. J. O'Rourke</I>";
text[3] = "There are three kinds of people:<BR><BR>Those who MAKE things happen, Those who WATCH things happen, and Those that WONDER what happened!";
text[4] = "EVERYONE has a GREAT idea which requires MY money! - <I>mmerlinn</I>";
text[5] = "";

ztext = text[Getrandommod(text[0])];

if (ztext != ""){
d.writeln("<CENTER>");
d.writeln("<TABLE BORDER='3' BGCOLOR='lightblue' CELLPADDING='6' WIDTH='95%'>");
d.writeln("<TR>");
d.writeln("<TD><FONT FACE='arial, geneva, verdana, helvetica'>");
d.writeln("<CENTER>");
d.writeln("<FONT SIZE='+0'><FONT COLOR=" + linkcolor + "><B>" + ztext + "</B></FONT></FONT>");
d.writeln("</CENTER>");
d.writeln("</TD>");
d.writeln("</TR></TABLE>");
d.writeln("</CENTER>");
}
}

function Getrandommod(dv){
zz = new Date();
zz = Math.floor(zz.getTime()/1000);
zz = zz % dv + 1;
return zz;
}



mmerlinn

"Political correctness is the BADGE of a COWARD!"

 
Hi

mmerlinn said:
The ones with longer lists are in .js includes.
Well, and that is where your script does not help. Because the OP not only wants to pick a random item, but the ".js includes" must be random too. His/her list is not long, it is huge.

Anyway, the best solution was given first, all others are just kludges :
Einstein47 said:
Sounds like it would be more efficient to do this as a server-side script.

Feherke.
 
Einstein47,

I'll second what feherke said.

Now that I've fixed it by selecting a random script, if I were to try to tackle this with a server-side solution how would I proceed?
 
What server side language are you using - I am not so good with PHP or PERL, but I know ASP and JSP. Let me know, and I'll see if I can help.

Einstein47
There are no kangaroos in Austria!
[&#91;]Starbase47.com]
 
Hi

dcroe05 said:
if I were to try to tackle this with a server-side solution how would I proceed?
First choose the language. Personally I would suggest PHP.

If you have the names enumerated in a plain text file, one name in a line, this may be all :
Code:
<?php
$namelist=file([i]"/path/to/name/file"[/i]);
[b]echo[/b] $namelist[rand(0,count($namelist)-1)];
?>

Feherke.
 
First, I know next to nothing about any of those languages, but I'm resigned to the fact that it's time I learned.

I had initially considered a PHP script--my blog and BB are both PHP so I'm a little familiar with them but I rejected that idea. Last Sept/11--which is a big bandwidth day for a project like this--my site was shut down, not for bandwidth restrictions but because of too many PHP requests.

This is why I went with JS, because then the user's computer is responsible for executing the script.
 
Now that makes a lot of sense - pushing CPU requirements off to the client instead of the server. I could bet that Sept 11 is a big day for your site.

I would stay with the JS solution then. Unless you can get a beefy account that doesn't have a problem with millions of PHP requests. (well, maybe not millions, but a significant amount).

I think you have made a wise choice.

Einstein47
There are no kangaroos in Austria!
[&#91;]Starbase47.com]
 
Actually you'd be correct with "millions". On 9/11 I had about 1,000,000 site hits (before the site went down around noon), and because the site was then just a blog each site generated about 15 PHP requests.

Thanks for your help. By using the JS fix, I dropped the bandwidth requirement from about 390k to about 10k.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top