Skip navigation
Currently Being Moderated

Trouble link to external JS

Apr 7, 2013 2:28 PM



I'm working through . However I want to create a seperate js rather than include it within the html doc and I can't get their examples to work within a seperate js. Doesn't show any of the JS. What am I doing wrong?


<!doctype html>
<html lang="en">
    <meta charset="utf-8">
    <title>HTML5 Canvas</title>
    <script type="text/javascript" src="js/game.js"></script>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.





// JavaScript Document

// Original W3C code...didn't work! var c=document.getElementById("myCanvas");


var myCanvas = document.getElementById("myCanvas");

var ctx=c.getContext("2d");



  • Currently Being Moderated
    Apr 7, 2013 3:02 PM   in reply to bobobobcat

    It doesn't work because the external JavaScript file is linked to the page before the Document Object Model (DOM) is loaded. The JavaScript file is trying to use document.getElementById("myCanvas") before the element with that ID is created.


    Put this line just before the closing </body> tag:


    <script type="text/javascript" src="js/game.js"></script>


    Then it should work.

    Mark as:

More Like This

  • Retrieving data ...

Bookmarked By (0)

Answers + Points = Status

  • 10 points awarded for Correct Answers
  • 5 points awarded for Helpful Answers
  • 10,000+ points
  • 1,001-10,000 points
  • 501-1,000 points
  • 5-500 points