donderdag 9 augustus 2012

Add jQuery library to a webpart via code

How to load your jQuery library at the same time as your webpart?

Add the jQuery library reference via code to your webpart.

protected override void Render(HtmlTextWriter writer)
{
 writer.AddAttribute(HtmlTextWriterAttribute.Src, "/_layouts/1043/STYLES/myUZA/js/jquery-1.4.2.min.js");
 writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
 writer.RenderBeginTag(HtmlTextWriterTag.Script);
 writer.RenderEndTag();
}

Another option is to do it in a full javascript block. You write the javascript code, put it in a string and register the javascript block via C# code:

//Load the jQuery library if it's not yet loaded
string js = @"<script type=""text/javascript"">
<">if (typeof jQuery == 'undefined') {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/_layouts/1043/STYLES/myUZA/js/jquery-1.4.2.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
}
</script>"
;

/// Register the javascript block
if
(!Page.ClientScript.IsClientScriptBlockRegistered(jsKey))
{
this.Page.ClientScript.RegisterClientScriptBlock(GetType(), "jQueryLib", js, false);
}

 

Geen opmerkingen:

Een reactie posten