Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

编写 CNZZ 工具函数 #3

Closed
Dream4ever opened this issue May 17, 2018 · 0 comments
Closed

编写 CNZZ 工具函数 #3

Dream4ever opened this issue May 17, 2018 · 0 comments
Labels
Front-end Everything you see and experience JS Javascript Statistics Everything about data

Comments

@Dream4ever
Copy link
Owner

Dream4ever commented May 17, 2018

需求描述

自己之前只是以最原始的方式给各个网站的前端页面添加了 CNZZ 统计代码,还有很多可以改进的地方,初步罗列如下:

  • 在页面中隐藏 CNZZ 生成的 HTML 元素
  • 加载完统计代码之后,再通过 JS 往页面中添加内部样式(和上面是同一个需求?)
  • 根据当前域名,加载对应的统计代码
  • 编写成 NPM 包,一次编写,到处使用

关于上面列出的第一项,CNZZ 统计代码用的是下面这种形式,最终会生成文字链接。但是由于 Chrome 的安全设置,会在浏览器控制台中出现第二段的提示代码,也就是说只有统计功能,但并不会显示文字连接。为了安全起见,还是需要在 CSS 中设置好样式,隐藏 CNZZ 统计内容。

<script src="https://s11.cnzz.com/z_stat.php?id=1260367303&web_id=1260367303" language="JavaScript"></script>` 
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

方案调研

Google Analytics 与国内各家统计服务的对比

CNZZ 统计原理

自己编写 JS 插件 / NPM 包

现成的库/组件

应用过程

参考了 import和export用法总结raychenfj/vue-uweb,把函数写在 addcnzz.js 中:

const AddCnzz = () => {
  const hostName = window.location.hostname;
  const sites = [
    {
      domain: 'abc',
      id: '1234567890',
    },
    {
      domain: 'def',
      id: '9876543210',
    },
  ];
  const site = sites.find(ele => hostName.match(ele.domain)) || null;
  if (site) {
    const script = document.createElement('script');
    script.src = `https://s11.cnzz.com/z_stat.php?id=${site.id}&web_id=${site.id}`;
    document.body.appendChild(script);
  }
}

export default AddCnzz;

然后在 vue-cli 中用 import 指令引用它,最后在需要的地方,调用 AddCnzz() 函数就可以了。

要点总结

写一个自己的工具函数其实很简单嘛!

@Dream4ever Dream4ever added Statistics Everything about data Front-end Everything you see and experience JS Javascript labels May 17, 2018
@Dream4ever Dream4ever changed the title CNZZ 编写 CNZZ 工具函数 Jun 17, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Front-end Everything you see and experience JS Javascript Statistics Everything about data
Projects
None yet
Development

No branches or pull requests

1 participant