O código subjacente do Firefox DevTools, que é escrito em JavaScript e HTML, é um aplicativo complexo. Devido à complexidade e à quantidade de trabalho em andamento, a equipe do DevTools fez todo o possível para carregar o mínimo possível. Além disso, a equipe tem um sistema de importação e inicialização preguiçosa de objetos quando eles são necessários. Eu dediquei um pouco de tempo para reduzir o inicializador, vamos dar uma olhada!
O sistema se baseia em aproveitar as vantagens do Object.defineProperty‘s get para inicializar um objeto quando necessário:
// Lazily initializes an object's property until it's used
function lazyGet(hostObj, name, initializer) {
let defined = false;
Object.defineProperty(hostObj, name, {
get: function () {
// If not already defined, define it by executing
// its initializer and setting it as value
if (!defined) {
defined = true;
// Overrides the original property definition
// which is the initializer
Object.defineProperty(hostObj, name, {
configurable: true,
enumerable: true,
value: initializer.apply(hostObj),
writable: true,
});
return hostObj[name];
}
},
configurable: true,
enumerable: true
});
}
Com a função lazyGet a propriedade que o senhor deseja só é inicializada e processada quando seu getter é chamado:
// Don't define window.myProp until someone tries to use it
// Thus, if it's never used, it's never initialized
lazyGet(window, "myProp", () => {
return { message: "Hello!" };
});
// window.myProp is now undefined, since it hasn't been requested yet
// Use it for something, which triggers initialization and returns its value
console.log(window.myProp.message);
// Using it again doesn't initialize again, since it was already created
console.log(window.myProp.message);
// And it can be reassigned later on:
window.myProp = null;
O inicializador do Mozilla é muito mais complexo, pois também atua como um carregador, mas o senhor entendeu a ideia. Sempre pensamos em carregar recursos de forma preguiçosa, mas também é bom pensar em inicializar propriedades, pois elas podem não ser necessárias! Mantenha uma pegada pequena se puder!