Link to JS files from site Style library

When you create your custom masterpage you will probably  need to embed javascript file. There are two ways to deploy JS files in your custom solution:

  • 14 hive (usually under layouts folder)
  • Somewhere in your content (usually Style library is a good place)

This post is about when you deploy JS to Style library. There are benefits of this approach – for specialized JS files, when you want to be able to edit it without a need of package upgrade.

You can achieve linking in several ways, some better that others:

1. This is safest way – you are linking to the right location wherever your portal sits on the root level URL for web application or somewhere under managed path. E.g. your link will be valid for http://portal and http://portal/sites/teamsite.

[sourcecode]<SharePoint:ScriptLink ID="ScriptLink1" Name="~SiteCollection/Style Library/My custom/JS/my-menu.js" runat="server" />[/sourcecode]

2. You can link like you would in HTML page but it will not work for sites on managed paths.

[sourcecode]<script type="text/javascript" src="/Style Library/My custom/JS/my-menu.js "></script>[/sourcecode]

3.Do not try this way even if it looks valid. This way only works for CssLink control but not for ScriptLink. If you try you will get the error.

[sourcecode]<SharePoint:ScriptLink ID="ScriptLink1" Name=" <% $SPUrl:~SiteCollection/Style Library/My custom/JS/my-menu.js %>" runat="server" >[/sourcecode]

One Response to “Link to JS files from site Style library”

Leave a Reply