Some Web applications (I'm thinking about Disqus and LiveFyre) create <script>
tags via Javascript, and via Javascript specify that the new scripts be loaded asynchronously. Why do they create the tags via Javascript? Instead of simply doing:
<script src="..." async>
An example:
This is how Disqus instructs website owners to load comments:
<script type="text/javascript">
var disqus_shortname = ...
(function() {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] ||
document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
And the src = ...disqus.com/embed.js
address is simply a redirect to a static script on another Disqus server, apparently independent of the disqus_shortname.
Why not instead tell people to use this piece of code:
<script>
var disqus_shortname = ...
</script>
<script src="http://direct-address-to-the-embed.js-script" async>
Or even simpler, just one line:
<script src="http://the_disqus_shortname.disqus.com/embed.js" async>
?
(P.S. I added one answer below. Please do add other answers too :-))
I can think of one uncertain (no. 1) and two likely reasons (no. 2 and 3):
[Edit] But reasons 2 and 3 are moot points — Disqus could simply do this despite of my reasons 2 and 3:
[/Editi]
(Perhaps old browsers that doesn't understand the
async
attribute completely ignore the whole<script ... async>
tag? Instead of ignoring onlyasync
and loading the script synchronously?)Perhaps Disqus would like to be able to genereate the embedded script dynamically, or redirect to different scripts, depending on website settings (although it seems as if Disqus currently always redirects to the same
embed.js
script always). Without having users reconfigure their Disqus code.Using a redirect allows Disqus to tell the browser to cache the-scripts-that-is-redirected-to for a long amount of time, but at the same time makes it possible to quickly redirect to another script. At the cost of 1 redirect per download / fetch-from-browser-cache. This was suggested here: https://stackoverflow.com/a/10098250/694469