Adding JavaScript to SharePoint Online

Microsoft does not recommend changing the master page in SharePoint Online. Though custom master pages are still supported, but you cannot completely control when the next updates are applied, that may break your customization. With this limitation, adding any scripts always comes across as a challenge.

For a page specific functionality, scripts can be easily added using a Content Editor Web Part, but there is no direct way to add scripts across the site. A much talked about way to add scripts in SharePoint Online is using JavaScript Injection. This approach though interesting, has a lot of overhead if all you want, is to add a script reference to all pages. It uses Custom Actions with a SharePoint Add In and has a bigger footprint overall. I think, it makes sense to use this approach if you are already building an Add In for additional functionality, so all your code remains in a single solution.

While trying to figure out a way to setup bread crumbs for one of our sites, I came across another way to add scripts by using PnpPowerShell commands. The command set includes “Add-SPOJavaScriptLink“, that allows to add a single JavaScript link to any SharePoint Online Site.

Here is a sample command:

PS:> Add-SPOJavaScriptLink Name jQuery Url https://code.jquery.com/jquery.min.js Sequence 9999 Scope Site

Important parameters:

  • Sequence here can be used to add multiple JavaScript Links in a particular order. For example: Jquery.js, followed by JqueryUI.js and custom.js
  • Name is the unique identifier under which script will be registered. Can also be used to remove any specific script.

(Also, look at Add-SPOJavaScriptBlock – allows you to add a script as a string, instead of reference to script file. )

To remove, you can use Remove-SPOJavaScriptLink, that allows you to remove a specific link using name or remove all links for a site (after confirmation for each one of them).

Getting Started with PnpPowerShell Commands
GitHub has good documentation on getting started with PnpPowerShell commands. Installation requires installing the setup files and running Install-Module commands.

Quick TipYou may get following error while running this command: “The term ‘Install-Module’ is not recognized…”. Try running PowerShell command prompt as an administrator.

Advertisements

One thought on “Adding JavaScript to SharePoint Online

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s