Skip to content

Commit 41436cc

Browse files
committed
application.js: allow for relative URLs
When running Hugo with relative URLs, as is the case when a developer runs `hugo` in a regular checkout of this repository, there is no `https://` prefix, and therefore the current logic failed. Fix this logic, and while at it, simplify the preceding code a bit. Note that this logic needs further adjustment, then, for importing the `pagefind.js` library: This `import`, if relative, is relative to the location of `application.js` (which is not the case where `baseURLPrefix` is used to set `href` and `src` attributes, which are relative to the top-level directory of the site). This _happened_ to work before because the bug was hidden by the bug where `baseURLPrefix` was not adjusted correctly for `HUGO_RELATIVEURLS=true`. Signed-off-by: Johannes Schindelin <[email protected]>
1 parent 6540655 commit 41436cc

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

assets/js/application.js

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,12 @@ popped = 'state' in window.history;
2121
initialURL = location.href;
2222

2323
const baseURLPrefix = (() => {
24-
const scripts = document.getElementsByTagName('script');
25-
const index = scripts.length - 1;
26-
const thisScript = scripts[index];
27-
return thisScript.src.replace(/^.*:\/\/[^/]*(.*\/)(assets|js)\/[^/]+.js(\?.*)?$/, '$1');
24+
const thisScriptSrc =
25+
Array.from(document.getElementsByTagName('script'))
26+
.pop()
27+
.getAttribute('src');
28+
return thisScriptSrc
29+
.replace(/^(?:[a-z]*:\/\/[^/]*)?(.*\/)(assets|js)\/[^/]+.js(\?.*)?$/, '$1');
2830
})();
2931

3032
$(document).ready(function() {
@@ -338,7 +340,15 @@ var Search = {
338340
return;
339341
}
340342
(async () => {
341-
Search.pagefind = await import(`${baseURLPrefix}pagefind/pagefind.js`);
343+
const pagefindURL =
344+
`${baseURLPrefix}pagefind/pagefind.js`
345+
// adjust the `baseURLPrefix` if it is relative: the `import`
346+
// is relative to the _script URL_ here, which is in /js/.
347+
// That is different from other uses of `baseURLPrefix`, which
348+
// replace `href` and `src` attributes which are relative to the
349+
// page itself that is outside of /js/.
350+
.replace(/^\.\//, '../')
351+
Search.pagefind = await import(pagefindURL);
342352
const options = {
343353
ranking: {
344354
pageLength: 0.1, // boost longer pages

0 commit comments

Comments
 (0)