High-Performance Development - C#, VB, SQL, ASP.NET

Slogan Text

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:

    function SPCG_CalendarDragAndDrop()

Notice the tags surrounding the JavaScript.

  1. 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.
  2. Compose a file path to the JavaScript file using Page.Request.PhysicalApplicationPath.
  3. Create a new StreamReader instance passing in the file path.
  4. Read the entire file into a string. Close the StreamReader.
  5. 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();

        Page.ClientScript.RegisterClientScriptBlock(typeof(string), Key, Script);