This article describes how to read a file containing JavaScript and insert (register) the JavaScript into your web page. Suppose we have a file containing JavaScript code for a drag and drop calender. The file is named SPCG_CalendarDragAndDrop.js. The content of the file looks somewhat like:
<script>
function SPCG_CalendarDragAndDrop()
{
...
}
</script>
Notice the tags surrounding the JavaScript.
-
Call Page.Client.IsClientScriptBlockRegistered to determine if our script has already been inserted into the web page. If the script is already registered then return and skip the remainder of the routine.
-
Compose a file path to the JavaScript file using Page.Request.PhysicalApplicationPath.
-
Create a new StreamReader instance passing in the file path.
-
Read the entire file into a string. Close the StreamReader.
-
Register (insert) the JavaScript into the page
public void ScriptRegister()
{
string FilePath;
string Key = "SPCG_CalendarDragAndDrop";
StreamReader ReaderObj;
string Script;
if( Page.ClientScript.IsClientScriptBlockRegistered(Key)) return;
FilePath = Page.Request.PhysicalApplicationPath + "SPCG_CalendarDragAndDrop.js";
ReaderObj = new StreamReader(FilePath);
Script = ReaderObj.ReadToEnd();
ReaderObj.Close();
Page.ClientScript.RegisterClientScriptBlock(typeof(string), Key, Script);
}