Adding JavaScript, CSS and others to a WebPart using WSPBuilder

pmmaga picture pmmaga · Mar 11, 2010 · Viewed 8.6k times · Source

So, I'm trying to do what I thought was a simple task... But I'm not getting anywhere... All I want to is to get some .js and .css files loaded by my WebPart. I'm using VS2008 + WSPBuilder. I've googled a lot about this but I couldn't find a decent answer. What I would like to know:

  • Where in the directory structure should I place those files? (eg. 12/TEMPLATE/OTHER? 80/wpresources/assembly_name?)

  • How can I reach those files? (using a relative path? getting the full path by some method?)

  • And finally, how can I add those files to the page's <head>?

Thanks in advance.. I've lost all my morning in these questions and i'm considering a career change! ;)

Answer

pmmaga picture pmmaga · Mar 11, 2010

Ok, after two cigarettes and more efficient google searches I found the solution.. Hope this helps someone in the same trouble as I was!

  • The right place to those extra files is in 12/TEMPLATE/LAYOUTS/1033/yourapp/

  • If they are in this place, the path to those files is /_layouts/1033/yourapp/yourjs.js

  • If you want to add a JavaScript file to the head of the page, place this code in the CreateChildControls() method:

    string scriptPath = "/_layouts/1033/yourapp/yourjs.js";
    if(!this.Page.ClientScript.IsClientScriptBlockRegistered(scriptPath))
    this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), scriptPath,
    "<script language=\"javascript\" src=\"" + scriptPath + "\">");
  • If you want to add a CSS file to the head of the page, place this code in the CreateChildControls() method:

    CssLink cssLink = new CssLink();
    cssLink.DefaultUrl = "/_layouts/1033/yourapp/yourcss.css";
    this.Page.Header.Controls.Add(cssLink);

Well, hope you found this helpfull!