Why is it that services like Google and Facebook use document.createElement('script')
instead of just <script>
?
The Google Analytics snippet:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
could be written as just:
<script src="//www.google-analytics.com/ga.js" type="text/javascript"></script>
and Facebook's like button:
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=xxx";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
could be simplified as just:
<script src="//connect.facebook.net/en_GB/all.js#xfbml=1&appId=xxx"></script>
I know there's some playing safe in them, but other than that I don't see why we shouldn't use the HTML5 ones?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…