ASP.NET 2.0 Master Pages - But how do I run JavaScript onLoad?
Great question. I hit this problem 5 minutes into developing my first Master Pages website. Inside the Master Page, you can define the usual JavaScript class file, or include in-page functions within the page header. The problem is that these functions will be included for all pages served, creating unnecesary bloat. I prefer to only include global functions within the Master Page script.
The easy solution here is to include any page-specific scripting within the content page, or in a small .js external file. After a cursory look at the content page, you'll see where the problem lies...as a content page doesn't define an entire HTML document, you won't have your usual <body> tag to wire the onLoad event to. And I'll bet you aren't interested in having the same onLoad event fire for every page, which wiring to the Master Page's body onLoad event would do.
Here's a method around the problem: In the content page where the onLoad event is needed, hook into the Page_Load event in the code-behind class, and create a textual script function. Then we can register the script using the ClientScript.RegisterStartupScript method. This will register the script you create and run as if the page's onLoad event was called separately...a pretty nifty way around, I think.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Initialize a stringbuilder object, much faster than string concatenation
Dim onloadScript As New System.Text.StringBuilder()
onloadScript.Append("<script type='text/javascript'>")
onloadScript.Append(vbCrLf)
onloadScript.Append("alert('This script is registered and run at the second page startup. Perfect!');")
onloadScript.Append(vbCrLf)
onloadScript.Append("</script>")
' Register script with page
Me.ClientScript.RegisterStartupScript(Me.GetType(), "onLoadCall", onloadScript.ToString())
End Sub
See it in action here. It is interesting to note that your newly registered function will fire before the Master Page's onLoad, but both functions will still fire.
One more suggestion: I've seen a lot of people use StringBuilders to increase performance, but then include normal string concatenation within the Append call: (like this: myStringBuilder.Append("All your base" + " are belong to us.") This is defeating the point: using the concatenation operator will cause a new string to be created and the value copied over...you've lost the benefit of the StringBuilder. It's better practice to call .Append twice to create the desired value.