Expand Minimize

Use AddJsLink to set and add a JS Link file.

PnP has an implementations to add JS Link files.

CheckId SPC029013
TypeName UseAddJsLink
Severity Warning
Type Assembly

Standard SharePoint CSOM On Premises

var scriptLinksEnumerable = scriptLinks as string[] ?? scriptLinks.ToArray();
if (scriptLinksEnumerable.Length == 1)
{
    var scriptSrc = scriptLinksEnumerable[0];
    if (!scriptSrc.StartsWith("http", StringComparison.InvariantCultureIgnoreCase))
    {
        var serverUri = new Uri(site.Context.Url);
        if (scriptSrc.StartsWith("/"))
        {
            scriptSrc = $"{serverUri.Scheme}://{serverUri.Authority}{scriptSrc}";
        }
        else
        {
            var serverRelativeUrl = string.Empty;
            if (site is Web)
            {
                serverRelativeUrl = ((Web)site).EnsureProperty(w => w.ServerRelativeUrl);
            }
            else
            {
                serverRelativeUrl = ((Site)site).RootWeb.EnsureProperty(w => w.ServerRelativeUrl);
            }
            scriptSrc = $"{serverUri.Scheme}://{serverUri.Authority}{serverRelativeUrl}/{scriptSrc}";
        }
    }

    var customAction = new CustomActionEntity
    {
        Name = key,
        ScriptSrc = scriptSrc,
        Location = SCRIPT_LOCATION,
        Sequence = sequence
    };
    ret = ((Site)site).AddCustomAction(customAction);
}
else
{
    var scripts = new StringBuilder(@" var headID = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var scriptsSrc = [];
for(var i = 0; i < scripts.length; i++) {
if(scripts[i].type === 'text/javascript'){
scriptsSrc.push(scripts[i].src);
}
}
");
    foreach (var link in scriptLinksEnumerable)
    {
        if (!string.IsNullOrEmpty(link))
        {
            scripts.Append(@"
if (scriptsSrc.indexOf('{1}') === -1)  {  
var newScript = document.createElement('script');
newScript.id = '{0}';
newScript.type = 'text/javascript';
newScript.src = '{1}';
headID.appendChild(newScript);
scriptsSrc.push('{1}');
}".Replace("{0}", key).Replace("{1}", link));
        }

    }

    ret = AddJsBlockImplementation(site, key, scripts.ToString(), sequence);
}

Standard SharePoint CSOM 365
var scripts = new StringBuilder(@" var headID = document.getElementsByTagName('head')[0];
var scripts = document.getElementsByTagName('script');
var scriptsSrc = [];
for(var i = 0; i < scripts.length; i++) {
    if(scripts[i].type === 'text/javascript'){
        scriptsSrc.push(scripts[i].src);
    }
}");

foreach (var link in scriptLinksEnumerable)
{
    if (!string.IsNullOrEmpty(link))
    {
        scripts.Append(@"
if (scriptsSrc.indexOf('{1}') === -1)  {  
    var newScript = document.createElement('script');
    newScript.id = '{0}';
    newScript.type = 'text/javascript';
    newScript.src = '{1}';
    headID.appendChild(newScript);
    scriptsSrc.push('{1}');
}".Replace("{0}", key).Replace("{1}", link));
    }

}

var jsAction = new CustomActionEntity()
{
    Name = key,
    Location = "ScriptLink",
    ScriptBlock = scripts.ToString(),
    Sequence = sequence
};
AddCustomAction(site, jsAction);

// Example becomes too long

Using PnP
site.AddJsLink(site, key, scriptLinks, 0)

To suppress this violation in managed code add the following attribute to the method which contains the instruction (available since SPCAF version v5.2). Learn more about SuppressMessage here.

// Important: Ensure to have #define CODE_ANALYSIS at the beginning of your .cs file
[SuppressMessage("Rencore.Analyzers.Assemblies.Rules.PnP.PnPBestPracticesGroup", "SPC029013:UseAddJsLink", Justification = "Provide reason for suppression here")]
Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.