Share via


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. It's recommended 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"
    });
}