Saturday, February 07, 2015

Right way to add CSS and JavaScript to SharePoint App Pages and Master-Pages

In SharePoint-Hosted App, there is a special way to embed your JavaScript and CSS.

Adding JavaScript:
To add JavaScript that resides in the "layouts\15" folder, just specify the file name:
<SharePoint:ScriptLink name="sp.core.js" runat="server" LoadAfterUI="true" Localizable="false" />

To Add JavaScript that resides in your app, for example in "Scripts" folder of your SharePoint-Hosted App:
<SharePoint:ScriptLink name="~site/Scripts/App.js" runat="server" OnDemand="false" LoadAfterUI="true" Localizable="false"></SharePoint:ScriptLink>

Adding CSS:
To add CSS to a SharePoint-Hosted App, you need to know how SharePoint works, its a bit different form that way JavaScript is embedded in the app. Initially I thought, I could use "<SharePoint:CssLink" just the way I used "<SharePoint:ScriptLink", but it wasn't true.

SharePoint uses "SharePoint:CssRegistration" and "SharePoint:CssLink" together to prevent duplication of CSS on the page. All you have to do is to register your CSS using the "SharePoint:CssRegistration" tag. Once registered, there already is a "SharePoint:CssLink" present in the master-page that collects all the registered CSS links and renders them on the page. In case you make a tiniest mistake while registering your CSS, it won't appear on the page. Here is how you can register for the SharePoint-Hosted apps:

<SharePoint:CssRegistration runat="server" Name="<% $SPUrl:~site/Content/App.css%>" After="corev15.css" />

Note that SharePoint adds all the CSS in an alphabetical order based on their file names. To control their order, you have to mention the CSS file "after" which your CSS file should be added. In above example, your CSS file will be rendered after "corev15.css" file. If you don't mention the "After" attribute, your CSS will be added before "corev15.css" since its named "App.css". If you have more than one CSS files you must mention full paths in the "After" attribute such as:

<SharePoint:CssRegistration runat="server" Name="<% $SPUrl:~site/Content/App2.css%>After="<% $SPUrl:~site/Content/App1.css%>" />

Remember, as mentioned before, "SharePoint:CssLink" is added only once and normally on the master-page. It collects all the registered CSS and adds their links. If your link doesn't appear despite the registration, make sure the "Name" is pointing to an absolute path.

No comments:

Post a Comment

Feel free to give constructive feedback or let me know if it was helpful.