Including the same JavaScript file on the client and the server
I've often been frustrated that there is no simple way to include a file of JavaScript functions on the server (ASP) and the client (the browser). I have a whole library of functions that convert, format, process and otherwise stretch and squeeze dates, strings, and xml documents. I keep copying code from a server-only file to a client-only file or vice versa. So today I finally fixed the problem by writing a function (to be executed on the server) that reads the file, chops off the silly <% and %> that the ASP include insists on, and writes it into the page. It's just:
function convert_to_client(filename) {
var fso = Server.CreateObject("Scripting.FileSystemObject");
var ts = fso.OpenTextFile(filename, 1); //ForReading
Response.Write("<script language='javascript'>");
var code = ts.ReadAll();
Response.Write(code.substring(code.indexOf("%")+1, code.lastIndexOf("%")));
Response.Write("</script>");
}
My test ASP is like this (the convert_to_client function is in script_converter.js):
<%@language="javascript" %>
<!-- #include file = "test.js" -->
<!-- #include file = "script_converter.js" -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<% Response.Write(convert_to_client(Server.MapPath("test.js"))); %>
<script language="javascript">
function runtest() {
client.innerText = test("from the client");
}
</script>
</head>
<body onload="runtest();">
server: <% Response.Write(test("from the server")); %>
<hr/>
client: <span id="client"></span>
</body>
</html>
Notice that test.js is included on the server, and also passed to the convert_to_client function to be written to the page so that it is available on the client. The test.js file is just this:
<%
function test(parm) {
return parm;
}
%>
The output when the test ASP page executes is:
server: from the server
--------------------------------------------------------------------------------
client: from the client
4:54:19 PM
|
|