Monday, November 20, 2017

Deploy JavaScript to a Site Collection or Web in Office 365 or On Premises + Dynamic Navigation Link

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.

3 comments:

  1. Really Thanks for sharing such an useful & Informative stuff...

    office 365 sharepoint training

    ReplyDelete
  2. Very nice post here thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.

    python Training in chennai

    python Course in chennai

    ReplyDelete