js Cannot call method 'appendChild' of null

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
var img=document.createElement("img");
img.src="http://pic1a.nipic.com/2009-01-06/20091619194270_2.jpg";
document.body.appendChild(img);

</script>

</head>

<body>
</body>
</html>

Uncaught TypeError: Cannot call method 'appendChild' of null。

只有在谷歌浏览器出现这个错误,其他IE系列,FF,Opera都是正常。找了一下原因,js的 document.body.appendChild(container);是在 body 之前运行的,这个时候,document.body 不存 在,即为 null ,所以 document.body.appendChild 就会报告上面的错误。把SCRIPT 代码包含到 <body></body> 里面就可以正常运行了  

原文地址:https://www.cnblogs.com/youxin/p/2668636.html