Tags

, ,

A lot of SharePoint developers are moving now to JavaScript as Microsoft intention is to concentrate as much as possible on client side development. In most of the cases, because they are coming from client side development, project is delivered with a lot of un-organized JavaScript code, loaded with scripts tags placed inside various web parts.

To organize the files, developers can now use some JavaScript loaders libraries like requirejs, and the next point is about how to use it in SharePoint development environment.

In general, when I need to work in client side, I used scriptmanager control to load the files I need. The reason I am doing this is because SharePoint client side development requires Microsoft Ajax library to be loaded and scriptmanager is doing this before specified files are loaded into the page.

<asp:ScriptManager id="ScriptManager" runat="server" EnablePageMethods="false" LoadScriptsBeforeUI="false" EnablePartialRendering="true" EnableScriptGlobalization="false" EnableScriptLocalization="true">
	<Scripts>
	<asp:ScriptReference Path="../../Scripts/require.js" />
	<asp:ScriptReference Path="../../Scripts/requireconfig.js" />
	<asp:ScriptReference Path="../../Scripts/master.js" />
	</Scripts>
</asp:ScriptManager>

Pay attention how to use LoadScriptsBeforeUI property. I would suggest you to have it set on false, otherwise you can affect SharePoint functionality.

Using scriptmanager we load require.js library, requireconfig.js and master.js. Requireconfig.js is our file containing common configuration for loading files. For example we can set loading orders for a calendar which is making use of a date and time utility file.

(function() {
	require.config({ 
	
		baseUrl: 'https://siteurl',
		
		// Paths
		paths: {
			DateTime: 'Utils/DateTime/DateTime',
			Calendar: 'Apps/Calendar/Calendar',
		},
		
		// Set dependendecies for js files
		shim: {
			'Calendar': {
				deps: ['DateTime']
			} 
		}
		
	});

}());

Master.js contains our custom code which should be a sort of dispatcher for loading files. Depending on page name, we might want to load some specific JavaScript files when page is loaded.

function pageLoad() {

	// Get the page name (making use of SharePoint builtin functionality here)
	JSRequest.EnsureSetup();
	var pageName = JSRequest['FileName'];
	
	if(pageName === 'AllPages.aspx') {
		
		// Additional configure requirejs for AllPages.aspx page
		require.config({
			paths: {
				AllPages: 'Pages/AllPages',
			},
			shim: {
				'AllPages': {
					deps: ['Calendar']
				} 
			}
		});
	}
	
	// Load required files for AllPages.aspx
	require(['AllPages'],function() {
		// Some logic can also be implemented here or in AllPages.js
	});

}

You can also combine this logic with built-in registerCssLink function (available in SharePoint 2013), which I wrote about it here, to load CSS file specific to current page.

Happy conding!!! 🙂

Advertisements