Recursive script inclusion with REQUIRE

One thing that tends to seriously limit the "best practices" when it comes to enterprise development and code reuse for Javascript is a lack of INCLUDE or REQUIRE functionality.

Code reuse and portability requires various functionality to be compartmentalized into individual .js files containing only related functionality, but on the web, including several files means making lots of unnecessary roundtrips, which can add up to a huge performance cost in the load time of your pages.

Good compartmentalized code also necessitates some sort of REQUIRE mechanism, which allows one unit of code (ie, script file) to specify when it won't run properly without another unit of code.

Thus, while working on a VB.Net project, I created this simple Javascript loader, which looks at the name of the directory in which an app resides, and then looks for a javascript file by that name and loads it. Directives can be placed in that Javascript file (and in any subsequent file) requiring the inclusion of additional script files.

Not only does this allow for easier inclusion of libraries as needed, but it also makes it easier to strip out unused code if/when it is no longer needed by an app.

This source code is also available in a C# version.

Imports System.IO

Partial Class javascript
	Inherits System.Web.UI.Page

	Private files As Stack

	Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
		files = New Stack()
		Response.ContentType = "application/x-javascript"
		Response.Write(GetFile("js/Contacts.js"))
	End Sub

	Private Function GetFile(ByVal path As String) As String
		Dim result As String = ""
		Dim filespec As String = HttpContext.Current.Request.PhysicalApplicationPath & path.Replace("/", "\")

		filespec = IO.Path.GetFullPath(filespec)

		'if the file is already loaded, then exit
		If files.Contains(filespec) Then Return ""

		'add this file to the loaded list
		files.Push(filespec)

		'load the file
		Dim s As String = ""
		Dim b As Boolean = False
		Try
			Dim sr As StreamReader = File.OpenText(filespec)
			Do
				b = True
				s = sr.ReadLine() & vbCrLf
				If s.IndexOf("//LIBRARY:") = 0 Then
					b = False
				End If
				If s.IndexOf("//REQUIRES:") = 0 Then
					b = False
					s = s.Replace("//REQUIRES:", "").Trim()
					result = result & GetFile(".." & s)
					s = ""
				End If
				result = result & s
			Loop While sr.Peek() <> -1 And Not b
			result = result & sr.ReadToEnd() & vbCrLf
			sr.Close()
		Catch ex As Exception
			result = vbCrLf & "/* Error loading file: " & filespec & " */" & vbCrLf
		End Try

		Return result
	End Function

End Class


This could be easily updated to work for CSS files as well.
comments powered by Disqus