Wednesday, December 25, 2013

How to add custom javascript to all pages on Sharepoint site

Did you ever have requirement to have your custom javascript available on all pages on the Sharepoint site? One of the way is to add regular script reference directly to the master page:

   1: <script type="text/javascript" src="http://example.com/myscript.js"></script>

In this case your script will be available on all pages which use custom master page. As you probably know in Sharepoint there are  master pages:

  • Custom master page – used for regular publishing pages, e.g. for public site view, including default.aspx. It is stored in SPWeb.CustomMasterUrl property;
  • System master page – used for system pages (e.g. application layout pages) and list views. Stored in SPWeb.MasterUrl.

So what to do if you use OTB master page for system views (e.g. seattle.master or oslo.master)? There are still several ways to add custom javascript. On of the easiest ways is to use CustomJSUrl attribute in onet.xml file of your web template:

   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <!-- _lcid="1033" _version="12.0.2220" _dal="1" -->
   3: <!-- _LocalBinding -->
   4: <Project Revision="5"
   5:          Title="$Resources:cmscore,IPPT_Project_Title;"
   6:          ListDir="Lists" xmlns:ows="Microsoft SharePoint"
   7:          UIVersion="15"
   8:          CustomJSUrl="/_layouts/15/myscripts/foo.js">
   9:     ...
  10: </Project>

With this approach it won’t be needed to add script reference to any master page (neither custom nor system), and script will be available on all pages (public and system).

No comments:

Post a Comment