[Javascript] Lazy Overriding
Let's see the following code
function copyText(text) {
if (navigator.clipboard) {
navigator.clipboard.writeText(text);
} else {
const input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
}
}
Any problem with this code?
So why everytime we call copyTextfunction, we have to do navigator.clipboardfeature detection again?
Feature detection won't change anyhow, in theory, we only need to do the feature detection once;
Of course, in this example, it won't cause any performance overload with feature detection, it's just an example, but there will be some cases, doing check everytime is time consuming when function get called .
The way to can resolve this issue is by using Function Lazy overriding:
function copyText(text) {
if (navigator.clipboard) {
copyText = (text) => {
navigator.clipboard.writeText(text);
};
} else {
copyText = (text) => {
const input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
};
}
copyText(text);
}
So for the first time exeuction:

After the first time:


浙公网安备 33010602011771号