The “SharePoint site collection scope” here includes both “Site pages” and “System pages”, which are reflected by two master pages in SharePoint “Site Master Page Settings”:

image

It’s very obvious and easy to apply a customized CSS file into this scope with the “Alternative CSS URL”:

image

But with JS file, it’s not that straightforward.

You can definitely create two customized master pages, one for “Site Master Page”, and the other for “System Master Page”, then refer the JS file in both of the master pages.

The problems are:
* You have to make a copy of the default master pages, then make changes to them to refer you JS, then change the SharePoint site to refer your customized master pages, it’s a bit overkill if you only want to refer a JS file.
* Changing “System Master Page” is NOT recommended.

The easiest way to implement this is to use the “ScriptLink” location of “CustomAction”.

  1. In your solution (works on both Farm and Sandbox solution), create a new module, then update the Elements.xml file to the below:
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <CustomAction 
            ScriptSrc="~SiteCollection/Style Library/Customized/js/your.js"
            Location="ScriptLink"
            Sequence="100">
    </CustomAction>
    </Elements>
    
  2. Create another module to deploy your.js into SharePoint to match the above location referred by ScriptSrc, the Elements.xml file looks like:
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <Module Name="Style Library"
            Path="Style Library\Customized\js"
            Url="Style Library/Customized/js">
    <File Path="your.js" Url="your.js" ReplaceContent="TRUE" />
    </Module>
    </Elements>
    
  3. In “your.js” file, you can simply add one line script for testing:
    if (window.console) console.log("custom js loaded.");
    
  4. Use a Site level feature to deploy the above two modules.

  5. Refresh your “Site pages” and “System pages”, you should be able to see the console log:

    image

Please Note:

Categories: SharePoint

Leave a Reply

Your email address will not be published. Required fields are marked *