jQuery

17
Jun 09

Including jQuery in DotNetNuke

As of DNN 5, jQuery is now included. This is great, unless you’re distributing a module and you want it to work with versions below 5 also. Fortunately there is a way to check if jQuery has already been included, thereby avoiding conflicts.

Notice the code is placed in the Page_PreRender event. This is an absolute must.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
protected void Page_PreRender(object sender, EventArgs e)
{
	if (HttpContext.Current.Items["jquery_registered"] == null)
	{
		// load jQuery
		RegisterJavascript("/DesktopModules/MyModule/js/jquery.js");
		// let other modules know about jQuery
		HttpContext.Current.Items.Add("jquery_registered", "true");
	}
 
	// load all the plugins
	RegisterJavascript("/DesktopModules/MyModule/js/jquery.foo.js");
	RegisterJavascript("/DesktopModules/MyModule/js/jquery.bar.js");
}

Here’s the RegisterJavascript method I use.

1
2
3
4
5
6
7
8
protected void RegisterJavascript(string fullPath)
{
	var script = new HtmlGenericControl("script");
	script.Attributes.Add("type", "text/javascript");
	script.Attributes.Add("src", fullPath);
 
	Page.Header.Controls.Add(script);
}

Now you can continue using jQuery without any worries of conflict.

One mistake that had me tripped up for a while was an include of jQuery in the skin. I didn’t realize it was there and I couldn’t figure out why none of my plugins worked. As a general rule I never include jQuery in the skin.