Coder Social home page Coder Social logo

memo's People

Contributors

melon avatar

Watchers

 avatar  avatar

memo's Issues

separation of concerns is not equal to separation of file types

What About Separation of Concerns?

One important thing to note is that separation of concerns is not equal to separation of file types. In modern UI development, we have found that instead of dividing the codebase into three huge layers that interweaves with one another, it makes much more sense to divide them into loosely-coupled components and compose them. Inside a component, its template, logic and styles are inherently coupled, and collocating them actually makes the component more cohesive and maintainable.

Prefer DEFER Over ASYNC

Prefer DEFER Over ASYNC

Not only can ASYNC scripts block rendering, they can also block synchronous scripts from executing. Presumably, scripts that are made synchronous are important for the critical content on the page, so delaying their execution causes further harm to the user experience.

A few conventions:

  • “script” typically means an external JavaScript file that has to be downloaded
  • “synchronous script” means a script done without ASYNC and DEFER which thus blocks HTML parsing and rendering

Starting with IE8 and followed soon after by other browsers, the concept of a preloader (or lookahead parser or speculative parser) was introduced where scripts could be downloaded in parallel.

To avoid synchronous scripts blocking the HTML parser, developers started figuring out ways to load scripts asynchronously. Not ALL scripts should be loaded asynchronously. If the script is needed to render the critical content on the page, then it should be loaded synchronously. But if the script isn’t needed for critical rendering, then it can be loaded asynchronously.

ASYNC scripts execute immediately once they finish downloading, and DEFER scripts execute after DOM Interactive.

DEFER scripts can never block synchronous scripts, while ASYNC scripts might depending on how quickly they download.

Solutions block downloading? block HTML parsing ? block HTML execution? block rendering?
pre-2006 sequential script loading BLOCK BLOCK BLOCK BLOCK
modern browser - preloaders NO BLOCK BLOCK BLOCK
async attribute - NO Probably Probably
defer attribute - NO NO Probably

如何理解不可变数据(immutable data)?

当一个对象中的某个属性发生改变时,我们不会再原数据对象上进行变更操作,而是复制出一个新的对象,对新对象中的那个属性进行变更,最后返回这个新的对象。因为对象一旦创建就不会改变,因此我们称之为不可变数据。不可变数据能让开发者无须关心数据对象会被意外篡改。

但是如果每做一次变更(即使是很小的变更),都要深拷贝出一个对象的话,CPU和内存消耗都会特别高,因此我们会一般采用一种叫结构化分享(structral sharing)的方式来实现不可变数据。当一个对象的某个属性变更时,我们首先会浅拷贝这个对象,然后在浅拷贝出来的对象中修改需要改变的属性,如果有多层嵌套,进行递归操作即可。

https://dev.to/viebel/structural-sharing-with-7-lines-of-javascript-2dnh

CSSOM

CSSOM

four main steps a browser must take to render a page:

  1. The web browser examines your HTML and builds the DOM (Document Object Model).
  2. The web browser examines your CSS and builds the CSSOM (CSS Object Model).
  3. The web browser combines the DOM and the CSSOM to create a render tree.
  4. The web browser displays your webpage.

a few key points about CSSOM

  1. Know that the CSSOM blocks anything from rendering.
  2. Know that the CSSOM has to be built every time you load a new page.
  3. Know that there is a relationship between the CSS your page loads and the javascript your page loads.

1. Know that the CSSOM blocks anything from rendering.

related to FOUC

2. Know that the CSSOM has to be built every time you load a new page.

even if CSS is cached, CSSOM is rebuilt every time pages reloads

3. Know that there is a relationship between the CSS your page loads and the javascript your page loads.

javascript may block CSSOM from built (e.g. blocking javascript code loaded before style sheets file is loaded)

Some concepts of React.js

The difference between Virtual DOM and DOM

Declarative vs Imperative

use MVVM architecture

React comes with a helping hand. The solution to problem 1 is declarativeness. Instead of low-level techniques like traversing the DOM tree manually, you simple declare how a component should look like. React does the low-level job for you - the HTML DOM API methods are called under the hood. React doesn’t want you to worry about it - eventually, the component will look like it should.

"Real" DOM vs Virtual DOM

deal with inefficiency of regular DOM

"Real" DOM: an abstraction of HTML code
Virtual DOM: an abstraction of "Real" DOM, thus an abstraction of an abstraction

Virtual DOM is lightweight and detached from the browser-specific implementation details.

React can do its computations within this abstract world and skip the “real” DOM operations, often slow and browser-specific.

ReactElement vs ReactComponent

ReactElement: Stateless
ReactComponent: Stateful

Microtask vs Macrotask

Microtask

  • process.nextTick
  • Promise
  • MutationObserver
  • Object.observe

Macrotask

  • setTimeout
  • setInterval
  • setImmediate
  • MessageChannel
  • UI rendering
  • network I/O
  • user I/O

Priority

microtask > macrotask
process.nextTick > Promise
after I/O, setImmediate > setTimeout, otherwise indeterminable

MutationObserver

let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
  characterData: true
})
timerFunc = () => {
  counter = (counter + 1) % 2
  textNode.data = String(counter)
}

MessageChannel

const mc = new MessageChannel();
mc.port2.onmessage = (event) => {
  console.log(event.data);
};
mc.port1.postMessage({ a: 1 });

Singleton in Javascript

Singleton in Javascript

var MySingleton = (function () {

  var INSTANCE;

  function MySingleton(foo) {
    if (!(this instanceof MySingleton)) {
      return new MySingleton(foo);
    }
    this.foo = foo;
  }
  MySingleton.prototype.bar = function () {
    //do something;
  };

  return {
    init: function () {
      if (!INSTANCE) {
        return INSTANCE = MySingleton.apply(null, arguments);
      }
      return INSTANCE;
    },
    getInstance: function () {
      if (!INSTANCE) {
        return this.init.apply(this, arguments);
      }
      return INSTANCE;
    }
  };

}());

css specificity

A selector's specificity is calculated as follows:

1.count the number of ID selectors in the selector (= a)
2.count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
3.count the number of type selectors and pseudo-elements in the selector (= c)
4.ignore the universal selector

https://www.w3.org/TR/css3-selectors/#specificity

visual formatting model

visual formatting model

  • block-level box

  • block container box

  • block box

  • inline box: inline-level(display: inline) && non-replaced elements

  • atomic inline-level box: inline-level && not inline box (replaced inline-level elments || display: inline-block || display: inline-table)

9.4.2
The width of a line box is determined by a containing block and the presence of floats. The height of a line box is determined by the rules given in the section on line height calculations.
A line box is always tall enough for all of the boxes it contains. However, it may be taller than the tallest box it contains (if, for example, boxes are aligned so that baselines line up). When the height of a box B is less than the height of the line box containing it, the vertical alignment of B within the line box is determined by the 'vertical-align' property.

9.6
An absolutely positioned box establishes a new containing block for normal flow children and absolutely (but not fixed) positioned descendants.

9.8.4
The containing block for a positioned box is established by the nearest positioned ancestor (or, if none exists, the initial containing block)
Although the parent outer box is not actually offset, setting its 'position' property to 'relative' means that its box may serve as the containing block for positioned descendants. Since the outer box is an inline box that is split across several lines, the first inline box's top and left edges (depicted by thick dashed lines in the illustration below) serve as references for 'top' and 'left' offsets.
image

The computed value is the same as the specified value, except for positioned and floating elements (see Relationships between 'display', 'position', and 'float') and for the root element. For the root element, the computed value is changed as described in the section on the relationships between 'display', 'position', and 'float'.
image

16.6
white-space: normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.
white-space: nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.

使用Charles进行手机端的https请求调试

使用Charles进行https调试能否成功的关键在于安装charles根证书。装完证书之后就能在Charles中查看https请求的明文了。

下面以Charles 3.10为例,讲一下安装charles根证书的步骤,以及安装完之后如何使用charles达到调试https的目的。

下载根证书

打开Charles,在上方的菜单栏依次展开并点击

Help > SSL Proxying > Save Charles Root Certificate...

保存根证书(该Charles版本保存的一般是crt类型的文件)到某处待用。

在手机上安装Charles根证书

参见 Using Self-signed SSL Certificates on iOS

调试https请求

关于如何使用Charles进行手机端普通http请求的调试这部分,暂时先不讲了。下面讲一下在已经能调试的基础上,如何能进一步调试https请求。

在菜单栏打开
Proxy > SSL Proxy Setting...
在弹框中勾选Enable SSL Proxying

image

然后用Charles抓包,可以看到目前还是无法查看https请求的明文的(以淘宝首页为例)

image

然后,选择某个https域名,右击之后在选项中点击Enable SSL Proxying
再在手机上请求一下淘宝首页,就能看到 https://www.taobao.com 请求的明文内容了

image

Using Self-signed SSL Certificates on iOS

Receiving Self-signed SSL Certificate

When you get a self-signed SSL certificate, I found that there're three ways you can use to transfer it to your iPhone:

  • as an attachment of an email received on your iPhone
  • through AirDrop to your iPhone
  • through a publicly accessible url that represents this certificate file

Install Self-signed SSL Certificate

After you received the certificate file, the iOS system will automatically prompt you with the following UI. Continue and complete the process.

View and Delete Self-signed SSL Certificate

If you need to know how many self-signed ssl certificates you have installed on your iPhone, do as the following steps.

deno

  • Secure defaults: Explicit permission must be granted for your Deno applications in order to access disk, network, and runtime environments.
  • Native TypeScript support: No tsconfig needed—Deno acts like a native TypeScript runtime. Under the hood Deno still transpiles and bundles TypeScript files.
  • Ability to import ES Modules directly from URLs: No more NPM—dependencies can be imported directly via URL or file path.

https://aws.amazon.com/cn/blogs/opensource/what-is-deno/

gitmoji

gitmoji

An emoji guide for your commit messages

some recommended emoji usage in messages related with github

stacking rule / z-index

https://stackoverflow.com/a/42076701

elements are stacked in this order:

  1. The stacking context’s root element (the element in this case)

  2. Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)

  3. Non-positioned elements (ordered by appearance in the HTML)

  4. Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)

  5. Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)

https://philipwalton.com/articles/what-no-one-told-you-about-z-index/

the algorithm of comparison x == y

The Abstract Equality Comparison Algorithm

The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:

  1. If Type(x) is the same as Type(y), then
    1. If Type(x) is Undefined, return true.
    2. If Type(x) is Null, return true.
    3. If Type(x) is Number, then
      1. If x is NaN, return false.
      2. If y is NaN, return false.
      3. If x is the same Number value as y, return true.
      4. If x is +0 and y is −0, return true.
      5. If x is −0 and y is +0, return true.
        Return false.
    4. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.
    5. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.
    6. Return true if x and y refer to the same object. Otherwise, return false.
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String,
    return the result of the comparison x == ToNumber(y).
  5. If Type(x) is String and Type(y) is Number,
    return the result of the comparison ToNumber(x) == y.
  6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  8. If Type(x) is either String or Number and Type(y) is Object,
    return the result of the comparison x == ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String or Number,
    return the result of the comparison ToPrimitive(x) == y.
  10. Return false.

true != 'true'

stacking context vs. containing block

In CSS 2.1, many box positions and sizes are calculated with respect to the edges of a rectangular box called a containing block. In general, generated boxes act as containing blocks for descendant boxes; we say that a box "establishes" the containing block for its descendants.

Stacking contexts are not necessarily related to containing blocks.

https://www.w3.org/TR/CSS2/visuren.html#propdef-z-index

For elements whose layout is governed by the CSS box model, any value other than none for the transform also causes the element to become a containing block, and the object acts as a containing block for fixed positioned descendants.

https://www.w3.org/TR/css-transforms-1/#propdef-transform

how does the browser position fixed elements in transformed element?

https://stackoverflow.com/questions/2637058/positions-fixed-doesnt-work-when-using-webkit-transform

https://stackoverflow.com/questions/21091958/css-fixed-child-element-positions-relative-to-parent-element-not-to-the-viewpo?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

Loading web fonts asynchronously

Loading web fonts asynchronously

So, to sum up: the default font loading behaviour in most browsers is terrible. You can’t just simply include @font-face rules in your CSS (at least, not until the font-display descriptor becomes widely supported). Instead, use a bit of JavaScript to load web fonts asynchronously. You can minimise the downsides of asynchronous loading by optimising for repeat visits and choosing appropriate fallback fonts. Help the browser discover fonts earlier by providing preload instructions.

By applying these principles you’ll take web fonts off the critical path and turn them into a true progressive enhancement. Your site’s visitors will thank you.

彻底弄懂 Http 缓存机制 - 基于缓存策略三要素分解法

彻底弄懂 Http 缓存机制 - 基于缓存策略三要素分解法

缓存存储策略

  • Cache-Control: public, private, no-cache, max-age, no-store
    • public, private, no-cache, max-age 客户端会缓存
    • no-store 客户端不会缓存

缓存过期策略

虽然浏览器缓存了资源,但是并不表示一定会使用,因为还有缓存是否 过期 的概念

  • no-cache, max-age 似乎既指定了缓存存储策略,也指定了缓存过期策略
    • no-cache: 需要缓存资源,但马上回过期
    • max-age: 需要缓存资源,但在max-age之后就会过期

Cache-Control指定的缓存过期策略比Expires有更高的优先级,也许是因为Cache-Control是http 1.1才新出的头字段

缓存对比策略

  • Last-Modified, Etags
  • If-Modified-Since, If-None-Match
    • 缓存过期:200
    • 缓存未过期:304

Heuristic expiration policies suggest defaulting to: 10% of the delta between Last-Modified and Date.

Last-Modified           10%                                Date         expire
           |-------------.-----------------------------------|-------------.

HTTP Cache Headers Explained

HTTP Cache Headers Explained

Caches work with content mainly through freshness and validation. A fresh representation is available instantly from a cache while a validated representation rarely sends the entire representation again if it hasn’t changed. In cases where there is no validator present (i.e. an ETag/Last-modified header), and a lack of explicit freshness info, it will usually (but not always) be considered uncacheable. Let’s shift our focus to the kind of headers you should be concerned about.

1. Cache-control

Every resource can define its own caching policy via the Cache-Control HTTP header.
Cache-Control directives control who caches the response, under what conditions and for how long.

Requests that don’t need server communication are considered the best requests: local copies of the responses allow the elimination of network latency as well as data charges resulting from data transfers. The HTTP specification enables the server to send several different Cache-Control directives which control how and for how long individual responses are cached by browsers among other intermediate caches such as a CDN.

Cache-control: private, max-age=0, no-cache

These settings are referred to as response directives. They are as follows:

Public vs. Private

A response that is marked “public” can be cached even in cases where it is associated with a HTTP authentication or the HTTP response status code is not cacheable normally. In most cases, a response marked “public” isn’t necessary, since explicit caching information (i.e. “max-age”) shows that a response is cacheable anyway.

On the contrary, a response marked “private” can be cached (by the browser) but such responses are typically intended for single users hence they aren’t cacheable by intermediate caches (e.g. HTML pages with private user info can be cached by a user’s browser but not by a CDN).

No-cache and No-store

“No-cache” shows that returned responses can’t be used for subsequent requests to the same URL before checking if server responses have changed. If a proper ETag (validation token) is present as a result, no-cache incurs a roundtrip in an effort to validate cached responses. Caches can however eliminate downloads if the resources haven’t changed. In other words, web browsers might cache the assets but they have to check on every request if the assets have changed (304 response if nothing has changed).

On the contrary, “no-store” is simpler. This is the case because it disallows browsers and all intermediate caches from storing any versions of returned responses i.e. responses containing private/personal information or banking data. Every time users request this asset, requests are sent to the server. The assets are downloaded every time.

max-age

The max-age directive states the maximum amount of time in seconds that fetched responses are allowed to be used again (from the time when a request is made). For instance, “max-age=90” indicates that an asset can be reused (remains in the browser cache) for the next 90 seconds.

s-maxage

The “s-” stands for shared as in “shared cache”. This directive is explicitly for CDNs among other intermediary caches. This directive overrides the max-age directive and expires header field when present. KeyCDN also obeys this directive.

The Cache-Control header is defined as part of HTTP/1.1 specifications and supersedes previous headers (i.e. Expires) used to specify response caching policies. Cache-Control is supported by all modern browsers so that’s all we need.

2. Pragma

The old “pragma” header accomplishes many things most of them characterised by newer implementations. We are however most concerned with the pragma: no-cache directive which is interpreted by newer implementations as cache-control: no-cache. You don’t need to be concerned about this directive because it’s a request header which will be ignored by KeyCDN’s edge servers. It is however important to be aware of the directive for the overall understanding. Going forward, there won’t be new HTTP directives defined for pragma.

3. Expires

A couple of years back, this was the main way of specifying when assets expires. Expires is simply a basic date-time stamp. It’s fairly useful for old user agents which still roam unchartered territories. It is however important to note that cache-control headers, max-age and s-maxage still take precedence on most modern systems. It’s however good practice to set matching values here for the sake of compatibility. It’s also important to ensure you format the date properly or it might be considered as expired.

To avoid breaking the specification, avoid setting the date value to more than a year.

4. Validators

ETag

This type of validation token (the standard in HTTP/1.1):

Is communicated via the ETag HTTP header (by the server).
Enables efficient resource updates i.e. no data transfer takes place if the resource doesn’t change.
The following example will illustrate this. 90 seconds after the initial fetch of an asset, initiates the browser a new request (the exact same asset). The browser looks up the local cache and finds the previous cached response but cannot use it because it’s expired. This is the point where the browser request the full content from the server. The problem with it is, that if the resource hasn’t changed, there is absolutely no reason for downloading the same asset that is already in the CDN cache.

Validation tokens are solving this problem. The edge server creates and returns arbitrary tokens, that are stored in the ETag header field, which are typically a hash or other fingerprints of content of existing files. Clients don’t need to know how the tokens are generated but need to send them to the server on subsequent requests. If the tokens are the same then resources haven’t changed thus downloads can be skipped.

The web browser provides the ETag token automatically within the “If-None-Match” HTTP request header. The server then checks tokens against current assets in the cache. A 304 Not Modified response will tell the browser if an asset in the cache hasn’t been changed and therefore allowing a renewal for another 90 seconds. It’s important to note that these assets don’t need to be downloaded again which saves bandwidth and time.

How do web developers benefit from efficient revalidation?
Browsers do most (if not) all the work for web developers. For instance, they automatically detect if validation tokens have been previously specified and appending them to outgoing requests and updating cache timestamps as required based on responses from servers. Web developers are therefore left with one job only which is ensuring servers provide the required ETag tokens. KeyCDN’s edge servers are fully supporting ETags.

Last-Modified

last modified header
The Last-Modified header indicates the time a document last changed which is the most common validator. It can be seen as a legacy validator from the time of HTTP/1.0. When a cache stores an asset including a Last-Modified header, it can utilise it to query the server if that representation has changed overtime (since it was last seen). This can be done using an If-Modified-Since request header field.

An HTTP/1.1 origin server should send both, the ETag and the Last-Modified value. More details can be found in section 13.3.4 in the RFC2616.

https://webcache.googleusercontent.com/search?q=cache:AyP1fVt6NlgJ:https://www.keycdn.com/blog/http-cache-headers/+&cd=16&hl=en&ct=clnk&gl=us

Tagged template

const x = (...args) => console.log(args);

x(`I like ${() => 'potato'} and ${() => 'tomato'}.`)
/*
["I like () => 'potato' and () => 'tomato'."]
*/
const x = (...args) => console.log(args);

x`I like ${() => 'potato'} and ${() => 'tomato'}.`
/*
0: (3) ['I like ', ' and ', '.', raw: Array(3)]
1: () => 'potato'
2: () => 'tomato'
*/
const y = (...args) => args[0][0] + args[1]() + args[0][1] + args[2]() + args[0][2];

y`I like ${() => 'potato'} and ${() => 'tomato'}.` 
/*
'I like potato and tomato.'
*/

above is the simplified mechanism that makes styled-components work.

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.