title | description | ms.date | ms.localizationpriority |
---|---|---|---|
Embedding JavaScript into SharePoint | Describes how to embed JavaScript into SharePoint, outlines why using namespaces is important, how to use namespaces, and provides additional references. | 06/13/2022 | medium |
You can use namespaces to avoid conflicts between your JavaScript customizations and standard SharePoint JavaScript or JavaScript customizations deployed by other developers.
The OfficeDev/PnP samples and solutions often include JavaScript code. In order to make the techniques easy to understand, these samples are usually simple and do not use namespaces when embedding JavaScript code into SharePoint. It is important to ensure that you follow the simple steps outlined in this article when you incorporate PnP samples into your solutions.
JavaScript is a loosely typed language. If you define a variable or function, and a variable or function with the same name already exists in the current context, the new value or implementation will replace the existing one. As a result, when you embed JavaScript code into SharePoint, it is easy to override standard SharePoint JavaScript code or customizations deployed by other developers. This can create conflicts that might be hard to identify and debug.
To avoid this, we recommend that you use custom namespaces for your JavaScript code.
The following example shows a simple pattern used to organize JavaScript code in namespaces and classes.
varMySolution=MySolution||{};MySolution.MyClass1=(function(){// private membersvarprivateVar1=1;varprivateVar2=2;functionprivateFunction1(){return"";}return{// public interfacemyFunction1: function(){returnprivateVar1;},myFunction2: function(){returnprivateVar2;}};})();
Functions defined in public interface can be invoked as:
MySolution.MyClass1.myFunction1();MySolution.MyClass1.myFunction2();
Because all your code uses the custom MySolution namespace, you can avoid any naming conflicts.
With the Minimal Download Strategy Feature enabled, Global Namespaces and Variables are cleared on MDS navigation.
To retain your Namespace, declare it as:
Type.registerNamespace('MySolution');
The Type Namespace is specific to SharePoint, for a generic JavaScript library use:
if(window.hasOwnProperty('Type')){Type.registerNamespace('MySolution');}else{window.MySolution=window.MySolution||{};}
The RegisterModuleInit
function declares a proper Type
Namespace.
Files attached with JSLink are not re-executed on MDS navigation, use the AsyncDeltaManager functions for that.