0

I have code and looking for best practice to load script inside the code.

This is how I manually included before - <script src='//test.test/adition/?'></script>

If the condition is true, I need to load <script src='//test.test/adition/?'></script> in script below.

I have found out that document.write() is not best practice, any advices?

<script type="text/javascript">
    var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    var element = document.getElementById('text');
    if (isMobile) {

    } else {
        console.log('error');    
    }
</script>
t.niese
  • 39,256
  • 9
  • 74
  • 101
Marko
  • 101
  • 1
  • 1
  • 9
  • You should not use user agent to differentiate between browsers or to detect if the site is loaded on a mobile device, this might lead to false assumptions about screen resolutions and about input devices. You should use feature detection instead. – t.niese Dec 26 '19 at 09:13

1 Answers1

0

Because it's an async action you should do it like this:

function loadScript(src) {
  return new Promise(function(resolve, reject) {
    let script = document.createElement('script');
    script.src = src;
    script.onload = () => resolve(script);
    script.onerror = () => reject(new Error(`Script load error for ${src}`));
    document.head.append(script);
  });
}
t.niese
  • 39,256
  • 9
  • 74
  • 101
voiys
  • 269
  • 5
  • 14
  • This answer is perfectly fine. But you should avoid answering a question that is a duplicate to an already highly voted question. Instead, you should mark the question as duplicate or write a comment linking to that duplicate. And if the duplicate is missing the technique you write in your answer you should add your answer to that duplicate. – t.niese Dec 26 '19 at 09:20
  • Sorry I couldnt find the question – Marko Dec 26 '19 at 09:27
  • @t.niese im on my phone and i dont know how to do it from the stack exchange app so i just answered the question – voiys Dec 26 '19 at 10:54