Przeglądaj źródła

refactor(js): shorten MathJax filename and minify + fingerprint assets

Remove fingerprinting from MathJax config JS to shorten its generated
filename. Reduces chance of JS filenames becoming too long for user's OS
to handle due to long Sha512 asset fingerprinting.

Minifies and fingerprints Academic's own JS for faster loading and to
prevent old versions getting cached by web browser.

Refactors Algolia search JS into its own file.

Close #768
See #794
George Cushen 6 lat temu
rodzic
commit
3ea332ca67

+ 23 - 18
static/js/search.js → assets/js/academic-search.js

@@ -1,6 +1,8 @@
 /*************************************************
- *  Academic: the website framework for Hugo.
+ *  Academic
  *  https://github.com/gcushen/hugo-academic
+ *
+ *  In-built Fuse based search algorithm.
  **************************************************/
 
 /* ---------------------------------------------------------------------------
@@ -149,25 +151,28 @@ function render(template, data) {
 * Initialize.
 * --------------------------------------------------------------------------- */
 
+// If Academic's in-built search is enabled and Fuse loaded, then initialize it.
+if (typeof Fuse === 'function') {
 // Wait for Fuse to initialize.
-$.getJSON( search_index_filename, function( search_index ) {
-  let fuse = new Fuse(search_index, fuseOptions);
+  $.getJSON(search_index_filename, function (search_index) {
+    let fuse = new Fuse(search_index, fuseOptions);
 
-  // On page load, check for search query in URL.
-  if (query = getSearchQuery('q')) {
-    $("#search-query").val(query);
-    initSearch(true, fuse);
-  }
-
-  // On search box key up, process query.
-  $('#search-query').keyup(function (e) {
-    clearTimeout($.data(this, 'searchTimer')); // Ensure only one timer runs!
-    if (e.keyCode == 13) {
+    // On page load, check for search query in URL.
+    if (query = getSearchQuery('q')) {
+      $("#search-query").val(query);
       initSearch(true, fuse);
-    } else {
-      $(this).data('searchTimer', setTimeout(function () {
-        initSearch(false, fuse);
-      }, 250));
     }
+
+    // On search box key up, process query.
+    $('#search-query').keyup(function (e) {
+      clearTimeout($.data(this, 'searchTimer')); // Ensure only one timer runs!
+      if (e.keyCode == 13) {
+        initSearch(true, fuse);
+      } else {
+        $(this).data('searchTimer', setTimeout(function () {
+          initSearch(false, fuse);
+        }, 250));
+      }
+    });
   });
-});
+}

+ 3 - 1
static/js/hugo-academic.js → assets/js/academic.js

@@ -1,6 +1,8 @@
 /*************************************************
- *  Academic: the personal website framework for Hugo.
+ *  Academic
  *  https://github.com/gcushen/hugo-academic
+ *
+ *  Core JS functions and initialization.
  **************************************************/
 
 (function($){

+ 72 - 0
assets/js/algolia-search.js

@@ -0,0 +1,72 @@
+/*************************************************
+ *  Academic
+ *  https://github.com/gcushen/hugo-academic
+ *
+ *  Algolia based search algorithm.
+ **************************************************/
+
+if ((typeof instantsearch === 'function') && $('#search-box').length) {
+  function getTemplate(templateName) {
+    return document.querySelector(`#${templateName}-template`).innerHTML;
+  }
+
+  const options = {
+    appId: algoliaConfig.appId,
+    apiKey: algoliaConfig.apiKey,
+    indexName: algoliaConfig.indexName,
+    routing: true,
+    searchParameters: {
+      hitsPerPage: 10
+    },
+    searchFunction: function (helper) {
+      let searchResults = document.querySelector('#search-hits')
+      if (helper.state.query === '') {
+        searchResults.style.display = 'none';
+        return;
+      }
+      helper.search();
+      searchResults.style.display = 'block';
+    }
+  };
+
+  const search = instantsearch(options);
+
+  // Initialize search box.
+  search.addWidget(
+    instantsearch.widgets.searchBox({
+      container: '#search-box',
+      autofocus: false,
+      reset: true,
+      poweredBy: algoliaConfig.poweredBy,
+      placeholder: i18n.placeholder
+    })
+  );
+
+  // Initialize search results.
+  search.addWidget(
+    instantsearch.widgets.infiniteHits({
+      container: '#search-hits',
+      escapeHits: true,
+      templates: {
+        empty: '<div class="search-no-results">' + i18n.no_results + '</div>',
+        item: getTemplate('search-hit-algolia')
+      },
+      cssClasses: {
+        showmoreButton: 'btn btn-outline-primary'
+      }
+    })
+  );
+
+  // On render search results, localize the content type metadata.
+  search.on('render', function () {
+    $('.search-hit-type').each(function (index) {
+      let content_key = $(this).text();
+      if (content_key in content_type) {
+        $(this).text(content_type[content_key]);
+      }
+    });
+  });
+
+  // Start search.
+  search.start();
+}

+ 4 - 4
layouts/partials/css/academic.css

@@ -806,8 +806,8 @@ article .article-metadata {
 .article-style video {
   margin-left: auto;
   margin-right: auto;
-  margin-top: 60px;
-  margin-bottom: 60px;
+  margin-top: 2rem;
+  margin-bottom: 2rem;
   padding: 0;
 }
 
@@ -818,8 +818,8 @@ article .article-metadata {
 }
 
 .article-style figure {
-  margin-top: 60px;
-  margin-bottom: 60px;
+  margin-top: 2rem;
+  margin-bottom: 2rem;
 }
 
 .article-style figure img {

+ 20 - 72
layouts/partials/footer.html

@@ -3,8 +3,7 @@
     {{/* Config LaTeX math rendering. */}}
     {{ if or .Params.math .Site.Params.math }}
     {{ $mathjax_config := resources.Get "js/mathjax-config.js" }}
-    {{ $secureJS := $mathjax_config | resources.Fingerprint "sha512" }}
-    <script src="{{ $secureJS.RelPermalink }}" integrity="{{ $secureJS.Data.Integrity }}"></script>
+    <script src="{{ $mathjax_config.RelPermalink }}"></script>
     {{ end }}
 
     {{/* Attempt to load local vendor JS, otherwise load from CDN. */}}
@@ -32,11 +31,6 @@
       {{ end }}
     {{ end }}
 
-    <script src="{{ "/js/hugo-academic.js" | relURL }}"></script>
-    {{ range .Site.Params.custom_js }}
-    <script src="{{ "/js/" | relURL }}{{ . }}"></script>
-    {{ end }}
-
     {{/* Maps JS. */}}
     {{ if eq .Site.Params.map 1 }}
       <script async defer src="//maps.googleapis.com/maps/api/js?key={{ .Site.Params.map_api_key }}"></script>
@@ -116,7 +110,6 @@
     {{ if eq .Site.Params.search.engine 1 }}
     {{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.fuse.url $js.fuse.version) $js.fuse.sri | safeHTML }}
     {{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.mark.url $js.mark.version) $js.mark.sri | safeHTML }}
-    <script src="{{ "/js/search.js" | relURL }}"></script>
     {{ end }}
 
     {{/* Algolia search engine. */}}
@@ -125,72 +118,27 @@
     {{ printf "<script src=\"%s\" integrity=\"%s\" crossorigin=\"anonymous\"></script>" (printf $js.instantsearch.url $js.instantsearch.version) $js.instantsearch.sri | safeHTML }}
     {{ end }}
     <script>
-      if ( $('#search-box').length ) {
-        function getTemplate(templateName) {
-          return document.querySelector(`#${templateName}-template`).innerHTML;
-        }
-
-        const options = {
-          appId: {{ .Site.Params.search.algolia.app_id }},
-          apiKey: {{ .Site.Params.search.algolia.api_key }},
-          indexName: {{ .Site.Params.search.algolia.index_name }},
-          routing: true,
-          searchParameters: {
-            hitsPerPage: 10
-          },
-          searchFunction: function(helper) {
-            let searchResults = document.querySelector('#search-hits')
-            if (helper.state.query === '') {
-              searchResults.style.display = 'none';
-              return;
-            }
-            helper.search();
-            searchResults.style.display = 'block';
-          }
-        };
-
-        const search = instantsearch(options);
-
-        // Initialize search box.
-        search.addWidget(
-          instantsearch.widgets.searchBox({
-            container: '#search-box',
-            autofocus: false,
-            reset: true,
-            poweredBy: {{ .Site.Params.search.algolia.show_logo | default false }},
-            placeholder: i18n.placeholder
-          })
-        );
-
-        // Initialize search results.
-        search.addWidget(
-          instantsearch.widgets.infiniteHits({
-            container: '#search-hits',
-            escapeHits: true,
-            templates: {
-              empty: '<div class="search-no-results">' + i18n.no_results + '</div>',
-              item: getTemplate('search-hit-algolia')
-            },
-            cssClasses: {
-              showmoreButton: 'btn btn-outline-primary'
-            }
-          })
-        );
+      const algoliaConfig = {
+        appId: {{ .Site.Params.search.algolia.app_id }},
+        apiKey: {{ .Site.Params.search.algolia.api_key }},
+        indexName: {{ .Site.Params.search.algolia.index_name }},
+        poweredBy: {{ .Site.Params.search.algolia.show_logo | default false }}
+      };
+    </script>
+    {{ end }}
 
-        // On render search results, localize the content type metadata.
-        search.on('render', function() {
-          $('.search-hit-type').each(function( index ) {
-            let content_key = $( this ).text();
-            if (content_key in content_type) {
-              $( this ).text(content_type[content_key]);
-            }
-          });
-        });
+    {{ $js_comment := printf "/* Source Themes Academic v%s | https://sourcethemes.com/academic/ */\n" .Site.Data.academic.version }}
+    {{ $js_bundle_head := $js_comment | resources.FromString "js/bundle-head.js" }}
+    {{ $js_academic := resources.Get "js/academic.js" }}
+    {{ $js_academic_search := resources.Get "js/academic-search.js" }}
+    {{ $js_algolia_search := resources.Get "js/algolia-search.js" }}
+    {{ $js_bundle := slice $js_academic $js_academic_search }}
+    {{ $js_bundle := $js_bundle | resources.Concat "js/academic-bundle-pre.js" | minify }}
+    {{ $js_bundle := slice $js_bundle_head $js_bundle | resources.Concat "js/academic.min.js" | fingerprint "md5" }}
+    <script src="{{ $js_bundle.RelPermalink }}"></script>
 
-        // Start search.
-        search.start();
-      }
-    </script>
+    {{ range .Site.Params.custom_js }}
+    <script src="{{ "/js/" | relURL }}{{ . }}"></script>
     {{ end }}
 
   </body>