Include Javascript and CSS files in your SharePoint 2010 visual Web Part

Standard

Add the Layout mapped folder in your SharePoint project (you can see here to have a guide to do it).

Add a folder with your project name (e.g. “coderpills”) inside the Layout folder (e.g. “Layout\coderpills”).

For Javascript files create the js folder and use the SharePoint:ScriptLink tag inside the ascx file:

<SharePoint:ScriptLink id="ScriptLink1" runat="server" Localizable="false" Name="coderpills/js/main.js" />

For CSS files create the css folder and use the SharePoint:CssRegistration tag:

<SharePoint:CssRegistration ID="CssRegistration1" runat="server" Name="/_layouts/coderpills/css/style.css" />

You can also reference images, inside the img folder, using the following url:

/_layouts/coderpills/img/picture.png

If you get an error “file not found” when your web part page is loaded, like the following:

"Cannot make a cache safe URL for "/some/path/to/file.xyz", file not found. Please verify that the file exists under the layouts directory."

you should check that:

  • CSS references starts with “/_layouts/”.
  • JS references have the attribute Localizable=”false”.
  • From Visual Studio, in the properties of CSS and JS files, the “Build Action” should be “Content” and “Deployment Type” should be “TemplateFile”.

Note: to be sure that files will be added to your project in Visual Studio with correct properties you should use “Add new item…” or “Add existing item…” from the Layout mapped folded.

References

http://abemiester.com/abemiester/post/Adding-javascript-files-to-your-SharePoint-2010-web-part.aspx

http://tommdaly.wordpress.com/2012/05/02/sharepoint-cssregistration-or-link/

http://sharepoint.stackexchange.com/questions/32984/where-to-put-javascript-files-problem-with-layouts

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s