[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:

posted @ 2024-11-23 22:41  Zhentiw  阅读(20)  评论(0)    收藏  举报