super-zz / issue-blogs Goto Github PK
View Code? Open in Web Editor NEW工作与学习中遇到的经验与问题总结
工作与学习中遇到的经验与问题总结
CA 证书”在 SSL/TLS 中的作用:
CA证书通常会对应几个文件:一个文件包含公钥,一个文件包含私钥
补充:
“非对称加密算法”从数学上确保了——即使你知道某个公钥,也很难(不是不可能,是很难)根据此公钥推导出对应的私钥。
然后浏览器随机生成一个“对称加密的密钥”(以下称为 k)。用 CA 证书的公钥加密 k,得到密文 k'
浏览器把 k' 发送给网站。
4. 网站收到浏览器发过来的 k',用服务器上的私钥进行解密,得到 k。
5. 至此,浏览器和网站都拥有 k,“密钥交换”大功告成啦。
核心概念:
入口
输出
loader
plugins
bat和sh的区别~
bat运行环境为windows
sh运行环境为linux
call
从一个批处理脚本中调用另一个批处理脚本,如果不用call直接调用将不会返回到当前文件并执行当前文件的后续命令
所有自由变量的查找,是在函数定义的地方,向上级作用域查找,不是在执行的地方。
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
取得是定义时上级作用域的this
普通函数this
谁执行this指向谁
/**
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);
}
}
}
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();
chromium官方文档,解释了dom->layoutObject->paintLayer->GraphicLayers的过程
https://www.chromium.org/developers/design-documents/gpu-accelerated-compositing-in-chrome
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方法
* @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))
wasm与rust结合更新canvas
https://www.hellorust.com/demos/canvas/index.html
webassembly用例
https://webassembly.org/docs/use-cases/
位图(bitmap),又称 栅格图 或 点阵图。
使用像素阵列来表示图像。
根据位深度,可将位图分为 1,4,8,16,24,32位图像 (2的多少次方)
监听自定义事件:
window.addEventListener("customEvent", event => {
console.log(event.detail);
});
派发自定义事件:
window.dispatchEvent(new CustomEvent("follow", {
detail: {
name: "..."
}
}));
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);
}
开启chrome中的一些设置 包括webrtc
about:flags
chrome中的媒体信息
chrome://media-internals/
当元素祖先的 transform 属性非 none 时,容器由视口改为该祖先。
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}}}
watch
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事件。
总结:
截至到chrome 75版本,测试此现象还是会触发iframe的reload事件。
当remove和append iframe时,会被认为是一个全新的实体
解决方案
避免改变iframe在dom中的位置
用其他方式达到同样的效果
0.2+0.7=0.89999999999
js数字都是以浮点数形式进行存储,有些小数以二进制表示位数是无穷的。
类库调用
Math.js
decimal.js
big.js
^(.):(.)$
"\1" : "\2"
hash
利用#后面触发浏览器的hashchange
window.onhashchange=function() {
let hash=location.hash.slice(1);
document.body.style.color=hash;}
三者区别
入参
call
返回值
call在原函数执行
bind返回新函数执行
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.