Friday, March 28, 2014

Loading JavaScript Libraries only when needed – SharePoint

With the current trend of moving to client side scripting, we can see so many lines of custom scripts are written in SharePoint applications. When comes to SharePoint Online environments, sometimes only practical option to implement some custom functionality is client-side scripting.

Usually most of the custom scripts written are required or used in few pages. This means there is no need for the script to be put on the master page. Of cause we can add these script references to the page layouts. But with so many scripted custom controls we will have to maintain lot of page layouts.

On the other hand there are so many SharePoint script files and we cannot say when and where we will use them.

Therefore it is really good if there is a technique that can be used to keep amount of scripts loading down to an acceptable level on page basis.

We can use ScriptLink in master page with OnDemand attribute set to true to register scripts. Then on a page, script can be requested to execute by using SP.SOD.execute or SP.SOD.executeFunc methods.

.html master page:
<!--MS:<SharePoint:ScriptLink language="javascript" name="SP.Search.js" OnDemand="true" runat="server" Localizable="false">-->
<!--ME:</SharePoint:ScriptLink>-->

.master master page:
<SharePoint:ScriptLink language="javascript" name="SP.Search.js" OnDemand="true" runat="server" Localizable="false">
</SharePoint:ScriptLink>

Page that require the script:
$("#MySearchButton").click(function () {
   SP.SOD.executeFunc('SP.Search.js', 'Microsoft.SharePoint.Client.Search.Query', SetSearchSettings);
});

var SetSearchSettings = function () {
   // search settings
};

Here SP.SOD.executeFunc ensures that the SP.Search.js file that contains the Microsoft.SharePoint.Client.Search.Query function is loaded and then runs the specified callback function SetSearchSettings. SetSearchSettings function is where I write my custom code.

Custom Script Files:
Use Script Editor webpart to add scripts/script references to the page without the need of changing the MasterPage or Page Layout. (Scripts added directly in page content will get removed automatically upon page save)
Script Editor webpart content:
<script src="/_catalogs/masterpage/myproject/js/custom-search-control.js" type="text/javascript"></script>

No comments: