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?