3

I just added SnapEngage to a client's site with the following chunk of code provided by SnapEngage:

<script type="text/javascript">
document.write(unescape("%3Cscript src='//www.snapengage.com/snapabug.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
SnapABug.addButton("1ff63c0c-0bf1-43e2-b9ae-08de517f08dc","0","55%");
</script>

I thought it was weird to have </script> and <script type="text/javascript"> in the middle so I took them out, but then the code stopped working. Why is that? Do they affect timing somehow?

Cyrcle
  • 1,363
  • 3
  • 13
  • 25
  • Wait, so you removed the script contents entirely? did you put them in the `` tag? – Matt Nov 14 '12 at 19:21
  • Possible duplicate of http://stackoverflow.com/questions/496646/how-does-the-location-of-a-script-tag-in-a-page-affect-a-javascript-function-tha?rq=1 – Sean Airey Nov 14 '12 at 19:29
  • This is interesting, it highlights how browsers parse scripts. Best guess is that when you remove the separators, the browser parsing the container script first, and attempting to call SnapABug.addButton, -then- it's handle the document.write. That's a guess though. – Mike Robinson Nov 14 '12 at 19:33

1 Answers1

5

The first script puts script tag into HTML which loads snapabug.js and loading this resource is synchronous. So executing next scripts, which is SnapABug.addButton(...), is suspended until the resource will be downloaded and interpreted. This way, SnapABug object is visible in the following scripts.

If you put all JavaScript code in one script tag, it is executed as one batch. There is no SnapABug object in global scope because the provided script has not been downloaded yet.

dreame4
  • 749
  • 5
  • 9