Search code examples
javascriptasp-classic

How to include a classic asp written in Javascript from another classic asp file also written in Javascript?


I am working on a classic ASP project and unfortunately cannot switch to another technology. I learned that it's possible to write server side classic ASP code in Javascript (ES3) so I did some investigation but I cannot find a way to include another JS based ASP file from my JS based ASP file.

Here is the JS based ASP file I want to import:

includejs.asp

<%@ Language=JavaScript %>

<%
function myFunction(p1, p2) {
    return p1 + p2;
}

%>

And I tried the following 2 ways, neither worked

myjs1.asp

<%@ Language=JavaScript %>

<script language="JScript" runat="server" src="./includejs.asp"></script>

<%
    // myFunction is from another file
    Response.Write(myFunction(20,2));
%>

myjs2.asp

<%@ Language=JavaScript %>

<!--#include virtual="./includejs.asp" -->

<%
    // myFunction is from another file
    Response.Write(myFunction(20,2));
%>

My findings

I was able to import a pure javascript file like the following with my first attempt

function myFunction(p1, p2) {
    return p1 + p2;
}

but I want to include a ASP wrapped javascript so that I can include other files from the included Js file too.


Solution

  • I finally figured it out. Thanks for @Flakes's comment about I shouldn't put <%@ Language=JavaScript %> again in the include file, which was exactly the reason why my second approach above didn't work.

    Here I put a more complicated working example just in case anyone needs it.

    myjs.asp includes lib.asp which includes lib2.asp

    myjs.asp - lib2() function is from lib2.asp which is included by lib.asp

    <%@ Language=JavaScript %>
    
    <!--#include file="lib.asp" -->
    
    <%
        Response.Write(lib());
        Response.Write(lib2());
    %>
    

    lib.asp

    <!--#include file="lib2.asp" -->
    
    <%
    function lib() {
        return "this is lib.asp";
    }
    %>
    

    lib2.asp

    <%
    function lib2() {
        return "this is lib2.asp";
    }
    
    function myFunction2(p1, p2) {
        return p1 * p2;
    }
    %>
    

    Many things can go wrong, so you have to be careful in every detail.

    One thing to note is that if you are using relative path like I do and your lib.asp is in the same directory, you have to use file=... instead of virtual=... during #include statement. Check here to see more details about file vs. virtual in include directive