devxlogo

A Server-Side Assist for Loading Client-Side JavaScript Code

A Server-Side Assist for Loading Client-Side JavaScript Code

f you’re at all involved with Web development, you know about AJAX (Asynchronous JavaScript and XML). And you probably noticed the astonishing proliferation of AJAX frameworks, which provide a unified set of libraries for writing AJAX applications more easily.

One of the reasons frameworks are so important is that JavaScript isn’t quite ready for programming in the large. Don’t get me wrong?the language is beautifully designed, but some of the subtleties of in-browser programming, to say nothing of cross-browser portability issues, can make JavaScript development something less than smooth. One example is its poor support for the include statement, which enables one file to draw in the contents of another?usually a file containing a useful library. Just about every language has a mechanism for this, and various Web technologies have a number of different ways of providing include functionality.

The AJAX frameworks solve these problems to one degree or another. Each one attempts to hide platform incompatibilities behind abstractions and adapt some of the metaphors of traditional programming language environments into the browser. However, the browser may not be the proper place to deal with the include limitation. This 10-Minute Solution suggests that you implement include on the server side (using a simple CGI script) rather than trying to get browsers to do it.


JavaScript doesn’t have a function that loads and executes a library file in the middle of executing a main program file. How do I implement this function in JavaScript when it doesn’t have an include directive?


Implement include on the server side using a simple CGI script.

Asynchronous Loading

Include is a pretty simple concept, so you might wonder why this would even be an issue. The answer may lie in the design of early browsers, as well as the more modern browsers that were derived from them. Asynchronous communications has always been essential to Web technology. When a browser loads a Web page, it finds tags that instruct it to load other items?images, applets, frames, scripts, and so on. These items, of course, can be on other servers. Because the browser is loading a number of items from potentially different locations, it loads them asynchronously and in parallel. That way, you can see the Web page that you have loaded from a very fast site, even while waiting for a huge image from a slow site to appear inside that page.

Browsers are so carefully built around asynchronous interaction that it can be tricky to force synchronous loading. If you’ve done any client-side Java programming (especially in the early days of Java), you probably remember how complicated image loading was. You couldn’t just call a function that returned a fully loaded image. Instead, you would initiate a load, and the loading process would invoke callbacks to inform you about the progress of the load, culminating in a final message that told you everything was loaded.

Many programmers wrote their own libraries to take care of all of this (sometimes using threads), so that they could just call a function that returned a fully loaded image. But it was easy to get this code wrong, especially when trying to run the code on different platforms with different patterns of I/O behavior. Finally, such functions moved into the standard Java libraries, but it took quite a while.

So, how does this apply to JavaScript include? It’s pretty much the same thing. JavaScript doesn’t have a function that loads and executes a library file in the middle of executing a main program file. It doesn’t have include as we know it from other languages.

Asynchronous Loading of JavaScript

You can have one script load another in a number of ways. The most common is to simply write a script tag to the end of the document:

  document.write( "" );

The problem with this is that mycode.js is going to be loaded later. The following example shows why this is a problem:

// ...document.write( "" );mylibrary_function( 1, 2, 3 );// ...

This code attempts to load mylibrary.js and then call a function from that library called mylibrary_function(). But the first line only starts the include. It tells the browser to start loading and then continues to the second line, which tries to call the function. But the library isn’t loaded yet, and the function isn’t defined. So the call to mylibrary_function() will fail. (Actually, it probably will fail. I can’t really predict what the browser will do, because the many JavaScript implementations in the numerous browser versions in use today are not consistent.)

This kind of include, then, is a hack. You’ll find some workarounds for these problems as well, such as sleeping or breaking scripts into pieces, but these are also hacks, and they have still more problems of their own.

The XMLHttpRequest Solution

Most AJAX frameworks get around these problems by implementing some kind of include statement. They usually implement it with the XMLHttpRequest object, which is present in the most recent browsers.

The stated purpose of XMLHttpRequest is indicated by its name. It loads an XML file from a server using HTTP. However, it can be used to load any kind of file, including a .js file containing JavaScript code. Pass the loaded code to eval(), and it’s ready to be called.

However, XMLHttpRequest isn’t perfect. It exists in the latest browsers, but not everyone runs the latest browsers, so that won’t do. And you may be subject to the usual complications caused by different browser implementations.

Implement include() on the Server Side

After wrestling with these problems for a long time, I found a solution that took care of them completely. It also had the added benefit of making the loading process much faster. The answer was to implement include() on the server side. It’s important to realize that this is not the same thing as server-side include (SSI), which is a way of allowing .shtml files to include other .shtml files. I’m talking about implementing include on the server side for code that is activated on the client side.

For demonstration, take the following example. Although it is stripped down to the bare essentials, it illustrates the problems you would have when loading a large program.

Suppose you have one Web page called page.html:

JavaScript Include

This page loads the main JavaScript file of your JavaScript application: “main.js” loads the library script “mylibrary.js” and then calls main(), which in turn tries to use the library as follows:

// main.js// This doesn't always work.document.write( "" );document.close();function main(){  alert( "Here's main!" );  mylibrary_function();}main();

I structured the program this way because it reminds me of the familiar structure I have used in other languages. Unfortunately, it doesn’t work. By the time you want to use the code in “mylibrary.js”, it still hasn’t loaded.

Server-Side include

So, let’s change gears and implement the include on the server side. Here’s how it works:

  1. Instead of loading the URL (http://myserver.com/page.html), you use a CGI script (http://myserver.com/jsload.cgi?file=main.js).
  2. The jsload.cgi script takes a single CGI parameter, which names a JavaScript file to load?in this case, “main.js”.
  3. The jsload.cgi script reads main.js from the filesystem.
  4. The jsload.cgi script scans main.js for include("somefile").
  5. The jsload.cgi script replaces include("somefile") with the contents of the file (taking care not to get into an infinite loop in the case of mutually recursive includes).
  6. The jsload.cgi script sends the code to the browser.

This technique is primitive, but it works nicely and it’s quite fast. The speed probably comes from the fact that it creates only one connection. Using the traditional script-tag method may create a new connection for each script.

I ran informal performance tests with the browser and Web server on the same machine, and the results were impressive. My technique sped up the loading of 40 files (about 36k total in size) by a factor of 10.

The Server-Side Script

The following listing shows jsload.cgi, which is really a stub program?it determines which script is being loaded and then calls JSInclude::load():

#!/usr/bin/perluse CGI;use JSInclude;print "Content-type: text/html

";# What script are we loading?$cgi = new CGI();$file = $cgi->param( "file" );$file = "main.js";# Load the script.JSInclude::load( $file );
Security Warning: The jsload.cgi script, as shown above, is not secure. Since it takes a filename as a parameter, it might be possible (on some servers) to load files that shouldn’t be loaded, potentially providing a backdoor vulnerability. Please make sure your permissions are set in such a way that this cannot happen.

JSInclude.pm is where the real action is. JSInclude::load() starts the process by calling include()?that’s the Perl include, not the JavaScript include. Before and after this, however, it prints a preamble and postamble (respectively). These are normally empty, but if you set the '$verbose' variable at the top, the preamble and postamble will time the entire loading process on the client side and display the total loading time.

The following listing shows JSInclude::include():

package JSInclude;my $verbose = 0;sub get_includes( $ ){  my ($filename) = @_;  my @includes = ();  if (open( SRC, $filename )) {    while () {      if (/^s*includes*(s*"(.*)"s*)s*;s*$/) {        my $filename = $1;        push @includes, $filename;      }    }    close( SRC );  }  return @includes;}sub include( $$ );sub include( $$ ){  my ($filename,$already) = @_;  if ($already->{$filename}) {    return;  }  $already->{$filename} = 1;  my $includes = get_includes( $filename );  foreach my $include (@$includes) {    include( $include, $already );  }  if (!open( SRC, $filename )) {    print "Can't open '$filename': $!
";    die;  }  print qq(
);  close( SRC );}sub preamble{  print EOF}sub postamble{  print EOF}sub load( $ ){  my ($startfile) = @_;  preamble();  include( $startfile, {} );  postamble();}1;

This function is responsible for reading the contents of the file, scanning it for include(...) statements, and doing the include itself. The actual scanning is done by the get_includes() function.

Note that the include(...) statement in the JavaScript is never executed; instead, it is replaced (here on the server side) by the contents of the included file. Also note that include() maintains a variable called $already, which is a hash containing the names of all the files that have already been included. Including a file multiple times isn’t necessary, and it in fact can lead to infinite loops.

A Cross-Platform include Hack

In the end, the technique described here is as much a hack as any other technique for JavaScript include. However, it relies only on CGI and Perl?two mature and predictable technologies, so you can expect your includes to work across all server and client platforms.

It’s also a lot faster.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist