2

I'm trying to figure out how to include a custom JavaScript file in the search results page in SharePoint online.

My main goal is to be able to change the URL format for certain types of files in the search results. I have learned about Display Templates and had some success in modifying them to include the custom logic I want, but since I want this logic to be easily portable across site collections and tenants, my idea is to prepare a script file that contains most of the logic and load that into the page, so that I only need to make minimal changes to the display templates to make use of the loaded script.

However, I can't figure out how to include my own script file in the results page:

  • I've tried editing SearchMain.aspx and SearchResults.aspx in both _catalogs/masterpage and in _catalogs/masterpage/14, but edits I make to these files don't seem to be reflected in the HTML shown in the search results.

  • I've tried simply adding a <script> tag to the the display template file, and the <script> tag does show up in the search results' HTML, but my browser (Chrome) doesn't even seem to try to request the script file. Perhaps because of the way the page is generated, the browser isn't acting on the <script> tag.

  • I've tried adding something like the following to the display template file, and this does succeed in loading the script, but it finishes loading after the page has already rendered, which is too late:

function loadScript(path) {
    var scr = document.createElement('script');
    scr.src = Srch.U.replaceUrlTokens(path);
    document.head.appendChild(scr);
}
if (!window.myCustomFunction) { loadScript('~sitecollection/SiteAssets/myCustomFile.js'); }
  • I've considered editing the site collection's master file to include the script there, but I'm not even sure which file to edit for this, and I don't really want to include the script in the global master file because it's only needed for the search results.

Can anyone shed some light on how I can reference my script from the search results?

1 Answer 1

2

The short answer is there can only be one section in the Display Template. So if you want to use an external file you need a script reference to the extra file. So inside the body tag you could create a script tag:

<script>
  $includeCSS(this.url, "~sitecollection/Style Library/myproject/mystyle.css");
  $includeLanguageScript(this.url, "~sitecollection/Style Library/myproject/myscript.js");
</script>

The longer answer is it depends on what you are trying to do. There are Control, Group, and Item Display Templates. Understanding what each is for and how they play together is an important step to understanding "where" your code should go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.