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
on the server side. It's important to realize that this is
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
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:
main(), which in turn tries to use the library as follows:
// This doesn't always work.
document.write( "<script src=\"mylibrary.js\"></script>" );
alert( "Here's 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.
So, let's change gears and implement the
include on the server side. Here's how it works:
- Instead of loading the URL (http://myserver.com/page.html), you use a CGI script (http://myserver.com/jsload.cgi?file=main.js).
file to loadin this case, "main.js".
- The jsload.cgi script reads main.js from the filesystem.
- The jsload.cgi script scans main.js for
- 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
- 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.