-4

I know they do the same thing more or less, its just the approach on how its done.

<script src="example.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript">
function OptanonWrapper() { }
</script>

<script type="text/javascript">

var x = x || [];
  (function(){
        setTimeout(function(){
      var d = document, f = d.getElementsByTagName('script')[0], s = d.createElement('script'); s.type = 'text/javascript';

      s.async = true; s.src = "example.js"; f.parentNode.insertBefore(s,f);

    }, 1);

  })();

</script>

--

I am not a native js programmer so your help would be greatly appreciated.

hehe1
  • 5
  • 1
  • 2
  • 1
    Erm. They're completely different...? Unless the external example.js has some code you haven't included. – evolutionxbox May 23 '18 at 08:50
  • @evolutionxbox - example.js does not have differing code. How exactly are they different? Sorry again not a js programmer so I have no idea. My understanding that both were fetching js from example.js – hehe1 May 23 '18 at 08:54
  • 1
    The first literally does nothing, if example js is empty. The second essentially creates a script tag with a link to example.js. --- Contrary to my first comment, it too does nothing. – evolutionxbox May 23 '18 at 08:57

1 Answers1

0

In the first example, the second <script> tag will only execute after example.js has finished loading.

In the second example, the <script> tag that loads example.js is created dynamically and inserted into the document (in a needlessly roundabout way, if I may add my own two cents), and it will start loading asynchronously, i.e. it does not delay the execution of any <script> tags after it. The same effect could be achieved this way:

<script src="example.js" async></script>
<script>
    function OptanonWrapper() { }
</script>

Read up on the <script> element on MDN for more details:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script

Máté Safranka
  • 4,081
  • 1
  • 10
  • 22
  • Thank you for your answer. YEs it does come across quite needlessly roundabout but it was contrstructed like that for google tag manager. Initially I did create a script like yours as it is the most simple method. But in GTM it would not work for whatever reason. I could not figure out why, but I found the second example online which did work within GTM. This is why I was wondering what the difference between the two was. – hehe1 May 23 '18 at 09:46