3

This is my first question and I hope I’m doing it right. Couldn’t find any solutions so far, have asked a few coding friends of mine, no sufficient answers yet. Here it goes:

I’m optimizing my side project SaaS, which depends on the users copy/pasting a JavaScript embed code into their Websites. Much like Google Analytics or Twitter require you to do.

When researching how the others do it, I always see one of the two following methods, and I really wonder what’s the difference between them.

Edit for clarification: both loaded scripts sit on external servers.

Method 1: “Standard embed script” like that:

<blockquote id="container">Hello!</blockquote>
<script src="//some.saas.tld/widget.js"></script>

This is what Twitter uses, and it seems to simply load the script which then modifies the <blockquote> element

Method 2: “Hacked apart embed script” like that:

<script> 
  var a = document.createElement('script'); 
  a.src = '//some.saas.tld/widget.js'; 
  parentNode.insertBefore(a); 
</script>

(this is just very basic to show what kind of embedding I mean – it won’t work, and the blockquote isn’t in this, because that’s not the point). Google Analytics does that, for example.

Question is: why do some services use the first method, and why do some use the second? To me, it seems like it’s creating the same results. What’s the PRO/CON?

I’m asking because it’s really tough to make users change the embed code once they have it working within their website’s code. So it’s important to get it right from the start.

Thanks!

Teesche
  • 31
  • 5

1 Answers1

1

The first loading call is basically a synchronous call. This will not allow the next script to load or execute if this is not completed.

However the second manual script loading is asynchronous. It will allow execution and loading of other scripts even after the script is not loaded fully.

There is good article which explain this behavior in details - Checkout the link - https://trevweb.me.uk/javascripthtml-synchronous-and-asynchronous-loading/

Ashvin777
  • 1,446
  • 13
  • 19
  • I don't think that's a correct answer, sorry. In both cases the loading type can be added like this: Method 1: ` – Teesche Aug 10 '17 at 10:32
  • @Teesche Ashwin is right. IE<10 does **not** support the async attribute. [MDN](https://developer.mozilla.org/de/docs/Web/HTML/Element/script) states: ' In older browsers that don't support the async attribute, parser-inserted scripts block the parser; script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.' – Pinke Helga Aug 10 '17 at 11:04