You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

消除代码重复:基于if-else条件构造exponea事件优化JavaScript代码

JavaScript代码优化方案

你的需求完全可以实现,核心思路是先初始化通用的事件参数,再根据判断条件动态追加需要的额外属性,最终只调用一次exponea.track方法即可,优化后代码如下:

window.onload = function () {
  // 获取分类配置数据
  const categorycollection = JSON.parse(document.querySelector('.pipa').getAttribute('data-globaltargeting'));
  // 整理需要匹配的类型数组,后续新增类型直接修改该数组即可
  const matchTypes = ['PatientPlusArticle', 'MedicineLeaflet', 'PatientInformationLeaflet'];
  // 初始化通用参数,仅声明一次即可
  const trackParams = {
    referrer: document.referrer,
    path: window.location.pathname
  };

  // 类型匹配时动态追加额外参数
  if (matchTypes.includes(categorycollection.Type)) {
    trackParams['category name'] = document.querySelectorAll('.breadcrumb-item')[1].querySelector('span').innerText;
    trackParams.Isprofessional = categorycollection.Type === 'PatientPlusArticle' ? 'Yes' : 'No';
  }

  // 统一调用一次track事件
  exponea.track('page_visit', trackParams);
}

本次优化的核心优势:

  • 消除了重复的exponea.track调用逻辑,通用参数仅维护一处,避免后续修改时出现两边参数不一致的问题
  • 用数组includes方法替代冗长的多条件或判断,可读性和可扩展性大幅提升,后续新增匹配类型只需往matchTypes数组中添加元素即可
  • 仅在类型匹配时才计算、追加额外参数,避免无用的全局变量声明,运行效率更高
  • 整体代码行数比原版本减少40%左右,逻辑更清晰易懂

如果需要进一步提升模块化程度,可将页面访问埋点的逻辑抽离为公共复用方法,示例如下:

// 抽离为公共埋点方法,项目任意位置需要触发page_visit事件都可直接调用
function trackPageVisit (extraParams = {}) {
  const baseParams = {
    referrer: document.referrer,
    path: window.location.pathname
  };
  // 合并基础参数和自定义额外参数
  const finalParams = Object.assign(baseParams, extraParams);
  exponea.track('page_visit', finalParams);
}

window.onload = function () {
  const categorycollection = JSON.parse(document.querySelector('.pipa').getAttribute('data-globaltargeting'));
  const matchTypes = ['PatientPlusArticle', 'MedicineLeaflet', 'PatientInformationLeaflet'];
  const extraParams = {};

  if (matchTypes.includes(categorycollection.Type)) {
    extraParams['category name'] = document.querySelectorAll('.breadcrumb-item')[1].querySelector('span').innerText;
    extraParams.Isprofessional = categorycollection.Type === 'PatientPlusArticle' ? 'Yes' : 'No';
  }

  trackPageVisit(extraParams);
}

内容的提问来源于stack exchange,提问作者devram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:39:02