Giter Club home page Giter Club logo

issue-blogs's People

Contributors

super-zz avatar

Watchers

 avatar  avatar

issue-blogs's Issues

基于CA的密钥交换原理 http + SSL/TLS = https

CA 证书”在 SSL/TLS 中的作用:

CA证书通常会对应几个文件:一个文件包含公钥,一个文件包含私钥

补充:
“非对称加密算法”从数学上确保了——即使你知道某个公钥,也很难(不是不可能,是很难)根据此公钥推导出对应的私钥。

  1. 当浏览器访问该网站,Web 服务器首先把包含公钥的证书发送给浏览器。
  2. 浏览器验证网站发过来的证书。如果发现其中有诈,浏览器会提示“CA 证书安全警告”
  3. 如果网站发过来的 CA 证书没有问题,那么浏览器就从该 CA 证书中提取出“公钥”。

然后浏览器随机生成一个“对称加密的密钥”(以下称为 k)。用 CA 证书的公钥加密 k,得到密文 k'

浏览器把 k' 发送给网站。
4. 网站收到浏览器发过来的 k',用服务器上的私钥进行解密,得到 k。
5. 至此,浏览器和网站都拥有 k,“密钥交换”大功告成啦。

webpack

核心概念:

  • 入口

  • 输出

  • loader

  • plugins

bat命令学习

bat和sh的区别~
bat运行环境为windows
sh运行环境为linux

call
从一个批处理脚本中调用另一个批处理脚本,如果不用call直接调用将不会返回到当前文件并执行当前文件的后续命令

闭包

所有自由变量的查找,是在函数定义的地方,向上级作用域查找,不是在执行的地方。

vuex actions与mutations区别

Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。

store中dispatch代码

Store.prototype.dispatch = function dispatch (_type, _payload) {
    var this$1 = this;

  // check object-style dispatch
  var ref = unifyObjectStyle(_type, _payload);
    var type = ref.type;
    var payload = ref.payload;

  var action = { type: type, payload: payload };
  var entry = this._actions[type];
  if (!entry) {
    if (process.env.NODE_ENV !== 'production') {
      console.error(("[vuex] unknown action type: " + type));
    }
    return
  }

  try {
    this._actionSubscribers
      .filter(function (sub) { return sub.before; })
      .forEach(function (sub) { return sub.before(action, this$1.state); });
  } catch (e) {
    if (process.env.NODE_ENV !== 'production') {
      console.warn("[vuex] error in before action subscribers: ");
      console.error(e);
    }
  }

  var result = entry.length > 1
    ? Promise.all(entry.map(function (handler) { return handler(payload); }))
    : entry[0](payload);

  return result.then(function (res) {
    try {
      this$1._actionSubscribers
        .filter(function (sub) { return sub.after; })
        .forEach(function (sub) { return sub.after(action, this$1.state); });
    } catch (e) {
      if (process.env.NODE_ENV !== 'production') {
        console.warn("[vuex] error in after action subscribers: ");
        console.error(e);
      }
    }
    return res
  })
};

result 返回一个promise 微任务非同步处理

this

场景:

  • 作为普通函数
  • 使用call apply bind
  • 作为对象方法被调用
  • 在class方法中调用
  • 箭头函数

箭头函数this
取得是定义时上级作用域的this
普通函数this
谁执行this指向谁

检测网络 JS代码

/**

interface INetworkDerection {
  maxTimes?: number
  intervalTime?: number
  requestUrl: string
}

export default class NetworkDerection {
  private maxTimes: number;
  private intervalTime: number;

  private timer: number | undefined;
  private requestUrl: string = '';
  private n: number = 0;
  private offline: boolean = false;
  private watcher: NetListeners;


  constructor(args: INetworkDerection) {

    this.requestUrl = args.requestUrl;
    this.intervalTime = args.intervalTime || 3 * 1000;
    this.maxTimes = args.maxTimes || 10;

    this.watcher = new NetListeners();
  }

  public start() {
    this.clearTimer();

    this.timer = window.setTimeout(() => {
      this.fetchStatus();

    }, this.intervalTime);

  }

  public stop() {
    this.clearTimer();
    this.n = 0;
  }

  private clearTimer() {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = undefined;
    }
  }

  private fetchStatus() {
    const that = this;
    const request = new XMLHttpRequest();

    request.timeout = 10 * 1000;

    request.open('head', this.requestUrl);

    request.onreadystatechange = function() {
      // offline
      if (this.readyState === this.DONE) {
        if (this.status === 0) {
          if (++that.n > that.maxTimes) {
            that.n = 0;
            that.offline = true;
            that.watcher.emit('offline');
          }
        } else {
          if (that.offline === true) {
            that.offline = false;
            that.watcher.emit('online');
          }
        }

        that.start();
      }
    };

    request.send();
  }
}

// 监听事件
const eventNames = ['online', 'pending', 'offline'];
let listeners: any[] = [];
export class NetListeners {
  public on(eventName: string, callback: () => void) {
    if (!eventNames.includes(eventName)) {
      throw new Error('NetworkDetections: no defined func name' + eventName);
    }
    if (!(eventName in listeners)) {
      listeners[eventName] = [];
    }

    listeners[eventName].push(callback);

    return this;
  }

  public off(eventName: string, callback: () => void) {
    let currentEvent = listeners[eventName];
    let len = 0;
    if (currentEvent) {
      len = currentEvent.length;
      for (let i = len - 1; i >= 0; i--) {
        if (currentEvent[i] === callback) {
          currentEvent.splice(i, 1);
        }
      }
    }
    return this;
  }

  public emit(eventName: string, args?: any) {
    console.log('%c' + eventName, 'background: yellow');

    this.checkEvent(eventName);

    let callbacks = listeners[eventName];

    if (callbacks) {
      callbacks.forEach((callback: any) => callback.apply(null, args));
    }
  }

  private checkEvent (eventName: string) {
    if (!eventNames.includes(eventName)) {
      throw new Error('NetworkDetections: no defined func name' + eventName);
    }
  }

}

B站粗暴点击 会员答题~

var i = 0;
var t;
var f = () => {

let l = document.querySelectorAll('.answer-outer').length;

if(i >= l) {
	i=0;
}
if(document.querySelectorAll('.answer-outer')[i]){
    document.querySelectorAll('.answer-outer')[i].click();
	i++;
} else{
	i = 0;
}

clearTimeout(t);
t=setTimeout(f, 1000);

}
f();

npm hook

prepublish: 在publish该包之前执行。(在包目录下执行npm install时也会执行)

postpublish: 在该包publish之后执行

preinstall: 在该包被install之前执行

postinstall: 在该包被install之后执行

preuninstall: 在该包被uninstall之前执行

postuninstall: 在该包被uninstall之后执行

preversion: 在修改该包的version之前执行

postversion: 在修改该包的version之后执行

pretest, posttest: 在该包内执行test时执行,其中pretest先于posttest

prestop, poststop: 在该包内执行stop时执行,其中prestop先于poststop

prestart,poststart: 在该包内执行start时执行,其中prestart先于poststart

prerestart, postrestart: 在该包内执行restart脚本时执行,其中prerestart先于postrestart。注意: 如果没有在scripts里显示指定restart脚本,则会自动调用stop,然后再start

闲时执行JS方法

/**
 * 闲时执行JS方法 
 * @author zhengyu
 * example:
 * let monitorTask = new MonitorTask();
 * let id = monitorTask.addMonitorTask({
 *   func: () => {console.log(1231231); },
 *   precedence: false
 * });
 * // 移除未被执行的事件
 * monitorTask.removeMonitorTask(id);
 */

interface IMonitorTask {
  // 监测用户多久未操作执行闲时方法
  intervalTime: number;
  // 如果有操作是否要多等待一段时间
  userTime: number;
}
interface IAddMonitorTask {
  // 闲时执行方法
  func: () => void;
  // ctx
  ctx?: object;
  // 是否下次闲时先执行 vvvvip~~
  precedence?: boolean;
}

let priorityQueue: any[] = [];
let timer: number | undefined;
let initEventListener = false;
let userDo = false;

export default class MonitorTask {
  private intervalTime: number = 100;
  private userTime: number = 300;

  constructor(args?: IMonitorTask) {
    if (args) {

      this.intervalTime = args.intervalTime;
      this.userTime = args.userTime;

    }

    !initEventListener && this.isEnterListener();
  }

  public addMonitorTask ({func, ctx, precedence}: IAddMonitorTask) {
    const instanceId = (Math.round(Math.random() * 1000) + Date.now()).toString(16);

    if (precedence) {
      priorityQueue.unshift({
        instanceId,
        func: () => {
          try {
            func.call(ctx);
          } catch (e) {
            console.error(instanceId, 'MonitorTask');
          }
        }
      });
    } else {
      priorityQueue.push({
        instanceId,
        func: () => {
          try {
            func.call(ctx);
          } catch (e) {
            console.error(instanceId, 'MonitorTask');
          }
        }
      });
    }

    // 暂无任务在等待执行
    if ( typeof timer !== 'number' ) {
      this.monitorTask();
    }

    return instanceId;
  }

  public monitorTask (name?: string) {
    if (typeof timer === 'number') {
      clearTimeout(timer);
      timer = undefined;
    }
    if (!priorityQueue.length) {
      return;
    }

    // 无操作 缩短执行时间
    if (!userDo) {
      this.intervalTime = Math.max( 0, Math.floor(this.intervalTime - this.intervalTime * 0.2));
    }
    // console.log('%c' + this.intervalTime, 'background: black; color: #fff');

    timer = setTimeout( () => {
      this.triggerTask();
    }, this.intervalTime);
  }

  public triggerTask () {
    const { func } = priorityQueue.shift();

    clearTimeout(timer);
    timer = undefined;
    func();

    // 无操作 单次结算
    if (userDo) {
      userDo = false;
    }

    // line up task
    if (priorityQueue.length) {
      this.monitorTask();
    }
  }

  // 队列删除
  public removeMonitorTask (instanceId: string) {
    const _index = priorityQueue.findIndex((item) => item.instanceId === instanceId);
    if (_index > -1) {

      priorityQueue.splice(_index, 1);

      console.info(`instanceId ${instanceId} exist in MonitorTask subScribers`);
      return true;
    }

    console.info(`instanceId ${instanceId} no exist in MonitorTask subScribers`);
    return false;
  }

  public dynamicTimer () {
    userDo = true;
    this.intervalTime = this.userTime;
    this.monitorTask();
  }

  public isEnterListener () {

    // 鼠标事件

    // 按下
    document.documentElement.addEventListener('mousedown', () => {
      this.dynamicTimer();
    }, true);
    // 移动
    document.documentElement.addEventListener('mousemove', () => {
      this.dynamicTimer();
    }, true);
    // 滚轮
    document.documentElement.addEventListener('wheel', () => {
      this.dynamicTimer();
    }, true);


    // 键盘事件 
    document.documentElement.addEventListener('keydown', () => {
      this.dynamicTimer();
    }, true);

    // 除 Esc, Tab, CapsLock, Shift, Fn, Ctrl, Alt 外任意键被按住. (连续触发)
    document.documentElement.addEventListener('keypress', () => {
      this.dynamicTimer();
    }, true);

    document.documentElement.addEventListener('keyup', () => {
      this.dynamicTimer();
    }, true);
  }
}

白屏时间和首屏时间

白屏时间:
指的是浏览器开始展示内容的时间。(地址栏输入网址点击访问直到浏览器出现内容)
计算白屏时间:
开始渲染body或者解析完head标签之后
可使用 Performance API 时
白屏时间 = firstPaint - performance.timing.navigationStart;

不可使用 Performance API 时
白屏时间 = firstPaint - pageStartTime

首屏时间:
指的是打开网站开始,到渲染首屏内容完成的时间。

正则集合

匹配html标签

var str = '<svg class="odd" id="odd">123</svg>';
var pattern = /<(\/)?svg[^>]*>/g;
console.log(str.match(pattern))

位图

位图(bitmap),又称 栅格图 或 点阵图。
使用像素阵列来表示图像。
根据位深度,可将位图分为 1,4,8,16,24,32位图像 (2的多少次方)

customEvent 自定义事件

监听自定义事件:

window.addEventListener("customEvent", event => {
  console.log(event.detail);
});

派发自定义事件:

window.dispatchEvent(new CustomEvent("follow", {
  detail: {
    name: "..."
  }
}));

使用JS加载webfont字体,可用storage缓存

FontFace()
使用URL指向的外部资源或ArrayBuffer构造并返回一个新的 FontFace 对象。
兼容性

var fontFace = new FontFace(family, source, descriptors);

family
指定一个名称,该名称将用作字体属性的字体面值。使用与@font-face的font-family描述符相同的值类型。
source
font source 可以为URL 或者 二进制
descriptors
A set of optional descriptors passed as an object. It can have the following keys:
family: Family
style: Style
weight: Weight
stretch: Stretch
unicodeRange: Unicode range
variant: variant
featureSettings: Feature settings

    var xhr = new XMLHttpRequest();
    xhr.responseType = "arraybuffer";
    xhr.open('GET','url',true);
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
            loadFonts(xhr.response);
        }
    }
    xhr.send();
    async function loadFonts(res) {
        const font = new FontFace('font', res);
        await font.load();
        document.fonts.add(font);
    }

vue .sync 语法糖~

vue提供对prop进行“双向绑定”的修饰符。
但是在tsx中,修饰符不可以直接用~~
追溯到它的原理~
子组件

this.$emit('update:title', newTitle)

父组件

<text-document
  v-bind:title="doc.title"
  v-on:update:title="doc.title = $event"
></text-document>

在vue中 语法糖是这样的

<text-document v-bind:title.sync="doc.title"></text-document>

在tsx中

public handle(e){
    this.visible = e;
}
<MyComponent visible={this.visible} {...{on: {'update:visible': this.handle}}}

vue watch与computed

watch

  1. 不支持缓存,数据变,直接回触发相应的操作;
  2. watch支持异步
  3. 监听函数接收两个参数,新值和旧值
  4. 当属性变化时,执行对应操作;
  5. 监听属性是data或props中的数据;
    immediate:组件加载时立即执行回调函数;
    deep:深度监听对象内部值,无法监听到数组的变动;

axios offline && 503 Forwarding failure

axios 是这样判断 offline的,
它认为错误已经被浏览器隐藏,如果是网络问题会触发onerror事件

// Handle low level network errors
request.onerror = function handleError() {
  // Real errors are hidden from us by the browser
  // onerror should only fire if it's a network error
  reject(createError('Network Error', config, null, request));

  // Clean up request
  request = null;
};

字符编码

由于每个国家语言不同,而机器只能处理数字,为了统一各国编码Unicode应运而生。
**:GB2312
日本:Shift_JIS
韩国:Euc-kr
通用:Unicode

Unicode把所有语言都统一到一套编码里
1-6个字节 避免存储空间的浪费

iframe在dom中改变位置后,会触发reload事件

现象:
iframe改变在dom中的位置时会触发reload事件。

总结:
截至到chrome 75版本,测试此现象还是会触发iframe的reload事件。
当remove和append iframe时,会被认为是一个全新的实体

解决方案
避免改变iframe在dom中的位置
用其他方式达到同样的效果

  1. flex-box 结合 order
  2. position

参考资料:
https://stackoverflow.com/questions/8318264/how-to-move-an-iframe-in-the-dom-without-losing-its-state

js浮点运算会产生误差

0.2+0.7=0.89999999999

js数字都是以浮点数形式进行存储,有些小数以二进制表示位数是无穷的。

类库调用
Math.js
decimal.js
big.js

vue 路由实现原理

hash
利用#后面触发浏览器的hashchange

window.onhashchange=function() { 
  let hash=location.hash.slice(1);
  document.body.style.color=hash;}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.