pavanarya

Let us share the knowledge

Injecting Java Script Dynamically

with 2 comments

˛.°★。˛ °.★** *★* *˛.
˛ °_██_*。*./ \ .˛* .˛.*.★**★ 。*
˛. (´• ̮•)*˛°*/.♫.♫\*˛.* ˛_Π_____. * ˛*
.°( . • . ) ˛°./• ‘♫ ‘ •\.˛*./______/~\*. ˛*.。˛* ˛. *。
*(…’•’.. ) *˛╬╬╬╬╬˛°.|田田 |門|╬╬╬╬ .
¯˜”*°••°*”˜¯`´¯˜”*°••°*”˜¯`¬´¯˜”*°´¯˜”*°••°*”˜¯`´¯˜”*°•~

Hi,
In this post i want to write about dynamic java script injection. This can also be called as on demand java script.

So let me describe you about my requirement.

I am having two buttons button1 and button2.let us assume that there is a java script code that consists of 1000 lines of code. Initially the first button is active and the second button is inactive. The 1000 lines of java script code is specific to second button(button2). And button2 will be active only after clicking the first button(button1).

Adding Javascript code dynamically using javascript

So my opinion is it is waste of loading the 1000 lines of javascript code at the time of page loading because that javascript is specific to the button2 and button2 is inactive at the time of pageload. So after clicking on button1 , button2 will be active and it will be better if we can load java script after clicking button1.

<input type="button" id="btn1" runat="server" value="Button1" name="Button1" onclick="callwebservice()"/>
    <input type="button" id="Button1" runat="server" value="Button2" disabled=disabled name="Button2" onclick="pavan()"/>

so i am creating 2 buttons and i am disabling the 2nd one. For the 1st button’s onclick event i am calling javascript function and inside that function i am creating another javascript function.

<script language=javascript>
            function callwebservice() {
                if (document.getElementById('dynscript') == 'undefined' || document.getElementById('dynscript')==null) {
                    
                    var script = document.createElement('script');
                    script.type = 'text/javascript';
                    script.text = 'function pavan() {alert("hai pavan");}';
                    script.id = "dynscript";
                    var head = document.getElementsByTagName('head')[0];
                    head.appendChild(script);
                    document.getElementById('Button2').disabled = false;
                    
               }

            }

    </script>

document.CreateElement() is used to create dom elements dynamically from javascript. So i am creating a script tag using document.createElement(‘script’).

script.text is used to assign the actual javascript code to the tag created.

so for the script created dynamically i am adding a javascript function pavan() {alert(“hai pavan”);}'; and i am adding an attribute id as ‘dynscript’. Atlast i am trying to get the head element of the page using document.getElementsByTagName(‘head’)[0]; and i am appending the javascript element created to the head tag using head.appendChild(script);.

Atlast i am enabling the the button2 using javascript as document.getElementById(‘Button2′).disabled = false;

Now in the button2’s click event i am calling the javascript function pavan() which is dynamically created on button1’s click event.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <script language=javascript>
            function callwebservice() {
                if (document.getElementById('dynscript') == 'undefined' || document.getElementById('dynscript')==null) {
                    var head = document.getElementsByTagName('head')[0];
                    var script = document.createElement('script');
                    script.type = 'text/javascript';
                    script.text = 'function pavan() {alert("hai pavan");}';
                    script.id = "dynscript";
                    head.appendChild(script);
                    document.getElementById('Button1').disabled = false;
                    
               }

            }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <input type="button" id="btn1" runat="server" value="Button" name="Button" onclick="callwebservice()"/>
    <input type="button" id="Button1" runat="server" value="Button1" disabled=disabled name="Button1" onclick="pavan()"/>

    </div>
    </form>
</body>
</html>

Injecting java script from code behind file using ScriptManager

In above example we saw how to inject java script from java script code itself. Now let us see how to inject java script from code behind file using ScriptMnagaer class.

initially let us create 2 asp.net button controls Button1 and Button2.For asp.net button controls onclick event actually calls the code behind event handler function. And OnClientClick is used to call the java script function.

<asp:Button  id="btn1" runat="server" text="Button1"
            onclick="btn1_Click" />
    <asp:Button  id="Button2" runat="server" text="Button2" Enabled=false OnClientClick="pavan();return false;"/>

So for Button1 i am calling btn1_Click event handler present in the code behind file.

protected void btn1_Click(object sender, EventArgs e)
    {
        Button2.Enabled = true;
        ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "myscript", "<script language='javascript'>function pavan() {alert('hai pavan');};</script>", false);
    }

in the above function i am enabling the button2 and adding the javascript code using RegisterClientScript.

RegisterClientScriptBlock is the static function present in the ScriptManager class.

i.public static void RegisterClientScriptBlock(
	Page page,
	Type type,
	string key,
	string script,
	bool addScriptTags
)
ii.public static void RegisterClientScriptBlock(
	Control control,
	Type type,
	string key,
	string script,
	bool addScriptTags
)

In our code we are using the RegisterClientSciptBlock as follows

ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "myscript", "<script language='javascript'>function pavan() {alert('hai pavan');};</script>", false);

in the above function the first parameter “this” refers to the current page.second parameter is typeof(Page) which will return type.
Third parameter is the key which is internally used by Scriptmanager class. 4th parameter is the actual javascript code that we want to inject. 5th parameter is used to indicate whether we want to embed the javascript code specified in the 4th parameter.I am passing false for 5th parameter as my javascript code in 4th parameter already contains .

Complete code which is using SciptManager:

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button  id="btn1" runat="server" text="Button1"
            onclick="btn1_Click" />
    <asp:Button  id="Button2" runat="server" text="Button2" Enabled=false OnClientClick="pavan();return false;"/>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btn1_Click(object sender, EventArgs e)
    {
        Button1.Enabled = true;
        ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "myscript", "<script language='javascript'>function pavan() {alert('hai pavan');};</script>", false);
    }
}












About these ads

Written by pavanarya

December 25, 2011 at 10:10 am

Posted in Asp.net, Java script

Tagged with

2 Responses

Subscribe to comments with RSS.

  1. this way you are actually having more LOC in a page. :)

    Sunil Singhal

    December 25, 2011 at 11:26 am

    • Hi Sunil,
      Thanks for your comment.But when i am viewing the code in firebug i didn’t see any extra code. But in case of using scriptmanager for calling either pagemethods or web services from javascript i agree that scriptmanager is going to include additional proxy javascript that enables us to perform ajax calls.But for registering the script block i think it will not add any extra code.Also i am sure that in the 1st case of my post there will not be any extra overhead(injecting js using js).

      pavanarya

      December 26, 2011 at 4:41 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 68 other followers

%d bloggers like this: