简体   繁体   中英

Are <script> tags outside <head> and <body> permitted in HTML?

Based on this blog post Optimizing the asynchronous Google Analytics snippet and the comments, I have come up with this optimized Google Universal Analytics snippet that is shorter, runs faster (albeit slightly) and breaks IE6/IE7/oldIE8 * compatibility.

+function(G,o,O,g){G.GoogleAnalyticsObject=O;G[O]||(G[O]=function(){(G[O].q=G[O].q||[]).push(arguments)});G[O].l=+new Date;g=o.createElement('script');g.src='//www.google-analytics.com/analytics.js';o.documentElement.appendChild(g)}(this,document,'ga');
ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');

However, when the snippet above is placed in the <head> , it inserts the Universal Analytics script as a child not of <head> , not of <body> , but of <html> , right between </head> and <body> .

关闭头部标签和打开身体标签之间的脚本

Although IE8+ and modern browsers seems to have no problem with that, I am still worried that it might break older mobile browsers or some other obscure and non-IE browser somewhere.

Is there anywhere in the HTML specs that describe how a browser should react to tags placed outside <head> and <body> ?

* Unpatched vanilla IE8 on Windows XP will abort page loading just like IE6 and IE7 and spew an HTML Parsing Error: Unable to modify the parent container element before the child element is closed (KB927917) error. After installing a cumulative security update, starting with KB980182 first released in April 2010 and included in subsequent updates (KB982381, KB2183461, KB2360131, KB2416400, KB2482017, KB2497640, KB2530548, KB2559049, KB2586448, KB2618444, KB2647516, KB2675157, KB2699988, KB2722913, KB2744842, KB2761465, KB2792100, KB2809289, KB2817183, KB2829530, KB2838727, KB2846071, KB2862772, KB2870699, KB2879017, KB2888505, KB2898785, KB2909921), fixes the problem.

Yes and Its better to have Javascript script tag at bottom

  • because these scripts block parallel downloads.
  • When a script is downloading, the browser will not start any other downloads.
  • helps in loading the page faster

Reference yahoo developers

this is considered best practice for wpo, as the body will render before firing off the script element.

i'm not sure if its valid, you'll have to check spec, or run it through the validator...but its pretty much sop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM