Get Thunderbird! Firefox 2

Misc. Stats For This Page

Operating Systems
Linux
Windows
Mac
Other

Browsers
Firefox
MSIE
Netscape
AOL
Safari
Opera
MSN
Search Bots
Other

Google
Web www.ckorp.net
Page loads - 1860.
This page last modified on 01 Nov 2007
Foxkeh banners for Firefox 2 Click here for your favorite eBay items
.l.o.a.d.  .e.x.t.e.r.n.a.l.  .v.a.r.i.a.b.l.e.s.
Have you ever needed to load a JavaScript variable from an external file from within a block of JavaScript (i.e. not using a <script src=???></script> in the header)? "No, why would you want to do that?" you say. Let's take look at the following example:

<script>
  if(my_id > 0){
    // do something useful with my_id
    ...
  }else{
    // my_id does not exists so get it from an external
    // php script that finds my id in a database based on IP
    // address and then echos back JavaScript
  }
</script>

Now you might say "Why not load my_id from the external file every time the page loads?". Multiple reasons: server load, session tracking, etc., etc. The trick is getting the JavaScript to load this external file in the middle of execution. You could try using the eval() statement but I have had mixed results with that.

So how else could this be accomplished? The answer is use the DOM. By using the DOM, we can add a <script src=???></script> in the head before or after the page has completely loaded. Here's the code:

<script>

  if(my_id > 0){
    // do something useful with my_id
    ...
  }else{
    // my_id does not exists so get it from an external
    // php script that finds my id in a database based on IP
    // address and then echos back JavaScript
    var e = document.createElement("script");
    e.src = "get_my_id.php";
    e.type="text/javascript";

    // now you can use either of the following depending on
    // where you want this new src to appear.

    // To make it appear just before the closing head tag use
    document.getElementsByTagName("head")[0].appendChild(e);

    // To make it appear just after the opening head tag use
    document.getElementsByTagName("head")[0].insertBefore(e,document.getElementsByTagName("script")[0]);

  }
</script>

The important thing to remember here is that even though you can add the code above the current running section of code, it does not necessarily mean that any variables in loaded in that code are currently available to the script. Sometimes they are sometimes they are not, it really depends on the platform/browser in question. In other words don't trust it. Generally, the onLoad event has not fired yet so you could use it to time when the variables are read.