SharePoint 2010: Programmatically Add Javascript or CSS to Pages in SandBox Web Part

SharePoint 2010: Programmatically Add Javascript or CSS to Pages in SandBox Web Part

When you are creating a farm solution, it is easy to include javascript files into site pages using a CustomAction. You can add the JavaScript file to _layouts folder and use as:

<CustomAction Location="ScriptLink" ScriptSrc="/_layouts/.../your_javascript_file.js" Sequence="100">

The problem is, in sandboxed solutions you are not allowed to deploy files to the file system (_layouts), and it is not possible to reference Assets files. I'd recommend you to use native SharePoint controls: CssRegistration and ScriptLink

Example

protected override void CreateChildControls()
{
    base.CreateChildControls();
    this.Controls.Add(new ScriptLink()
    {
        Name = "/_layouts/MyFolder/MyScript.js",
        Language  = "javascript",
        Localizable  = false
    });
    this.Controls.Add(new CssRegistration()
    {
        Name = "/_layouts/MyFolder/MyStyles.css"
    });
}
Leave a Comment
  • Please add 3 and 2 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Comments
  • Richard Mueller edited Revision 6. Comment: Modify title casing

  • Matthew Yarlett edited Revision 4. Comment: Formatted code. Minor changes to wording.

  • Patris_70 edited Revision 3. Comment: deleted (en-US) title

  • Gokhan Ozcifci edited Revision 2. Comment: Content modify and new title

  • Craig Lussier edited Revision 1. Comment: added en-US to tags and title

  • Gokhan Ozcifci edited Original. Comment: Edit tags,

Page 1 of 1 (6 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
  • Gokhan Ozcifci edited Original. Comment: Edit tags,

  • Craig Lussier edited Revision 1. Comment: added en-US to tags and title

  • Gokhan Ozcifci edited Revision 2. Comment: Content modify and new title

  • Patris_70 edited Revision 3. Comment: deleted (en-US) title

  • Matthew Yarlett edited Revision 4. Comment: Formatted code. Minor changes to wording.

  • Richard Mueller edited Revision 6. Comment: Modify title casing

Page 1 of 1 (6 items)