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 copyText
function, we have to do navigator.clipboard
feature 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:
标签:Lazy,Overriding,text,Javascript,clipboard,input,navigator,document,copyText From: https://www.cnblogs.com/Answer1215/p/18565209