Software Developer's Resources

Shopping Cart Systems
Mobile Text Marketing Solutions
Online Backup Solutions
ASP.NET Web Development
Skip Navigation Links.

How to Insert JavaScript into a Web Page

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 <script></script> 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.
  5. Close the StreamReader.
  6. 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);
    }