Scenario
- You have some JavaScript you'd like to inject into a page and want the simplest method of deploying it to all pages within a Site Collection or Web.
Issue
- You can do this via custom master pages, but then you break any future upgrades from Microsoft
- You can also do this via a Sandbox code solution, SharePoint Framework, or a SharePoint Add-In, but these are all overly complex for this simple task and may not work in some environments due to incorrect environment configurations
Resolution
- The simplest, fully supported way to do this is via a User Custom Action ScriptLink
- John Liu has a nice UI tool to simplify registering your code with each site/site collection
Example
- The following code example injects simple Javascript into each page to add a dynamic link to the left navigation menu (quick launch)
- I like to put these in Site Assets at the Site Collection root. If you don't have a Site Assets library, you can create one by opening the site in SharePoint Designer and double clicking the Site Assets link. You can also do this by enabling any feature that utilizes the Site Assets library. Otherwise, you can use a different library that everyone can read from.
- You will need the following 3 files. These should be saved into the Site Assets library at the site collection root site.
$(document).ready(function(){
//Fixes Chrome Scrolling problem and load of ECMAScript
if (typeof(_spBodyOnLoadWrapper) !== 'undefined'){
_spBodyOnLoadWrapper();
console.log('test');
MenuLastLI = $('#zz14_RootAspMenu li:last');
MenuLastLI.before('
<li class="static"><a class="static menu-item ms-core-listMenu-item ms-displayInline ms-navedit-linkNode" href="http://www.votematrix.com/"><span class="additional-background ms-navedit-flyoutArrow"><span class="menu-item-text">CUSTOM LINK</span></span></a></li>
');
}; });
- Click to open John Liu's configuration page (configure-page.aspx)
- Configure jQuery as Sequence 900 (so it loads first). Install Site Collection.
- Configure JSTest.js as Sequence 2000 (Loads after jQuery)
- That's it. The link should show on the left nav.