Michael Warren
Michael Warren

Reputation: 205

Dynamically adding js to asp.net file

In my Page_Load I identify the page header block from my master page and add javascript from an XML file to that part of the page.

It doesn't seem to be loading in time. If I explicitly put the script reference on the page, it works. But not when I load through the page_load event.

Should it be loaded sooner?

Upvotes: 3

Views: 10414

Answers (3)

Sunny
Sunny

Reputation: 3295

Use this here i have js folder on root and it work fine for me.

function addJavascript(jsname, pos) {
            var th = document.getElementsByTagName(pos)[0];
            var s = document.createElement('script');
            s.setAttribute('type', 'text/javascript');
            s.setAttribute('src', jsname);
            th.appendChild(s);

        }

 addJavascript('js/table.js', 'Head');

call addJavascript method with file path and parent tag where you want to add javascript file

Hope it works for you..

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68440

You're not adding any code so I'm not able to tell you what you're doing wrong. Instead, I'll tell you a valid way to add script references from code behind.

Something like this on Page_Load should do the trick

var js = new HtmlGenericControl("script");
js.Attributes["type"] = "text/javascript";
js.Attributes["src"] = "myFile.js";
Page.Header.Controls.Add(js);

Upvotes: 10

Rajesh Subramanian
Rajesh Subramanian

Reputation: 6490

You can't you put in following method in ur page,

protected void OnInit(EventArgs e)

Upvotes: 0

Related Questions