I recently encountered an interesting issue that I managed to resolve, but out of sheer curiosity, I would love for someone to shed some light on why this problem occurred.
Below is the snippet of my HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="three.min.js"></script>
<script src="OrbitControls.js"></script>
<script type="text/javascript" src="webgl.js"></script>
</head>
<body style="margin: 0;">
</body>
</html>
And here's a glimpse of my JS code:
var scene, camera, renderer;
init();
animate();
function init(){
scene = new THREE.Scene();
var width = window.innerWidth, height = window.innerHeight;
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
}
Unfortunately, I encountered an error stating "Uncaught TypeError: Cannot read property 'appendChild' of null."
Strangely, when I moved my webgl.js script within the body tag, it magically started rendering the canvas element correctly.
Why is there a need for the script to be within the body in order to append the DOM element? The renderer object clearly returns a canvas in the console, so what could possibly be causing this peculiar behavior?