Skip to content

51la统计&灵雀统计

不使用inject配置项外挂js,将51统计和灵雀统计直接集成在butterfly主题里,源码取自 anzhiyu-c/hexo-theme-anzhiyu/

  1. 修改主题配置文件,添加以下配置
yml
# 51a统计配置
LA:
  enable: false
  ck: # 51la ck
  LingQueMonitorID: # 灵雀ID
  1. 修改themes\butterfly\scripts\events\merge_config.js,填入默认值
diff
hexo.extend.filter.register('before_generate', () => {

  ...

  const defaultConfig = {
    ...

+   LA: {
+     enable: false,
+     ck: null,
+     LingQueMonitorID: null,
+   },

  }

  ...

  hexo.theme.config = Object.assign(defaultConfig, hexo.theme.config)
}, 1)
  1. 修改\themes\butterfly\layout\includes\head\config.pug,定义GLOBAL_CONFIG.LA51
diff
-
  let algolia = 'undefined';

+ let LA51 = 'undefined';
+ if (theme.LA && theme.LA.enable) {
+   LA51 = JSON.stringify(theme.LA)
+ }

  ...
  
script.
  const GLOBAL_CONFIG = {
    ...
+   LA51: !{LA51},
    highlight: !{highlight},
    ...
  }
  1. 修改themes\butterfly\source\js\main.js
diff
document.addEventListener('DOMContentLoaded', function () {
  let headerContentWidth, $nav
  let mobileSidebarOpen = false

+ function statistics51aInit() {
+   const loadScript = (url, charset = "UTF-8", crossorigin, id) => {
+     return new Promise((resolve, reject) => {
+       const script = document.createElement("script");
+       script.src = url;
+       script.async = true;
+       if (id) {
+         script.setAttribute("id", id);
+       }
+       if (charset) {
+         script.setAttribute("charset", charset);
+       }
+       if (crossorigin) {
+         script.setAttribute("crossorigin", crossorigin);
+       }
+       script.onerror = reject;
+       script.onload = script.onreadystatechange = function () {
+         const loadState = this.readyState;
+         if (loadState && loadState !== "loaded" && loadState !== "complete") return;
+         script.onload = script.onreadystatechange = null;
+         resolve();
+       };
+       document.head.appendChild(script);
+     });
+   };

+   const scriptUrls = [
+     { url: "https://sdk.51.la/js-sdk-pro.min.js", charset: "UTF-8", crossorigin: false, id: "LA_COLLECT" },
+     { url: "https://sdk.51.la/perf/js-sdk-perf.min.js", crossorigin: "anonymous" },
+   ];

+   Promise.all(scriptUrls.map(({ url, charset, crossorigin, id }) => loadScript(url, charset, crossorigin, id)))
+     .then(() => {
+       LA.init({ id: GLOBAL_CONFIG.LA51.ck, ck: GLOBAL_CONFIG.LA51.ck });
+       new LingQue.Monitor().init({ id: GLOBAL_CONFIG.LA51.LingQueMonitorID, sendSuspicious: true });
+     })
+     .catch(error => {
+       console.error("加载51a统计异常,本地加载403是正常情况:", error);
+     });
+ }

    ...

+ // 51la统计&灵雀统计
+ GLOBAL_CONFIG.LA51 && statistics51aInit();

  refreshFn()
  unRefreshFn()
})
  1. 使用,修改主题配置文件填入你的 ck 和 id 即可
yml
# 51a统计配置
LA:
  enable: false
  ck: # 51la ck
  LingQueMonitorID: # 灵雀ID

其中 ck、LingQueMonitorID 可以在 51la统计 | 51LA · 灵雀应用监控 后台找到

注意:有一个小问题,来自 sdk.51.la 的 cookie 会导致浏览器控制台出现一个 Third-party cookie will be blocked. Learn more in the Issues tab. 提示,在浏览器设置阻止第三方cookie即可