It is good practice to have often used functions in a separate file that could be loaded by any html- or JavaScript-file that needs the functions. I often create htm-files with html and Javascript and use the Content Editor Webpart on a webpart page or wiki page to use these small customizations. In SharePoint Online I was struggling with loading script files with a relative path like “../scripts/functionLib.js”, what should be fine, when my page is stored in the Site Pages library, like in this snippet:


<script src="../Scripts/functionLib.js"></script>

What happens? When having the file in a library in SharePoint Online, anything removes the two dots (“..”). The result: the script could not be found, the page does not behave as expected any more. The dots are not removed directly after I store the file in the library, it happens one or two days later.

So, I have to load the script file in any other way, but I still want to be able to use site or web relative paths. To solve this problem, the functions SP.SOD.registerSod and SP.SOD.executeFunc will do the trick. Here is a simple example for a script, where I additionally use the function SP.SOD.registerSodDep:


<div>
MyParameter:&nbsp;<span id="myParameter"></span>
</div>

<script type="text/javascript">

SP.SOD.registerSod('functionLib.js', _spPageContextInfo.webServerRelativeUrl + '/scripts/functionLib.js');
SP.SOD.registerSod('jquery.js', 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js');

SP.SOD.registerSodDep('functionLib.js', 'jquery.js');

SP.SOD.executeFunc('functionLib.js', null, function() {
	var myParam = getUrlParameter("myParam");

	$('#myParameter').html(myParam);
});

</script>

This example uses the webServerRelativeUrl member of _spPageContextInfo, where SharePoint stores the relative URL of the current web site. When the script is stored in the root site of the site collection, the member siteServerRelativeUrl could be used instead.

Advertisements