Search code examples
javascriptdom-events

How to move inline JavaScript from HTML to .js files


I'm working on creating a basic web based game using the HTML5 canvas and JavaScript. Although I have done some work with the HTML5 canvas before, it hasn't been too extensive and so it hasn't required too much JavaScript- meaning I wrote the JavaScript in script tags in my .html file.

With the file I'm currently working on, I'm now getting to the point where I need to separate the JavaScript from the HTML, since when I view the page in a browser, and click the 'start' button on the canvas, although it does perform the function it's meant to, it takes an age to do it... I assume because of the size of my .html file (most of which is JavaScript).

I have moved all of the JavaScript into separate files, with just one or two functions in each file, but I'm not sure how I then use those functions in my HTML page?

My HTML file currently looks like this:

<!DOCTYPE html>
<html>
<head>
<title>Home</title>

<section hidden>
<img id="StartButton" src="StartButton.png" alt="Start Button" width="179" height="180" href="javascript:drawLevelOneElements();"/>
</section>

<script src = "drawLevelOneElements.js" type = "text/javascript"></script>
<script src = "layers&analytics.js" type = "text/javascript"></script>
<script src = "startGameDrawGameElementsDrawStartButton.js" type = "text/javascript"></script>
<script src = "variables&preloadingImages.js" type = "text/javascript"></script>

</head>

<body onLoad="startGame()">
    <h1>Home</h1>
    <p1>The purpose of this website is to teach users the basic principles of running a business by playing the game below. <br /><br /></p1>
    <p2>
    
    <canvas id="gameCanvas" width="1000" height="500" style="border:1px solid">
    Your browser does not support the canvas element.
    </canvas>
    
    <br /><br /></p2>
    <p3>Use this paragraph to enter text that provides the user with instructions for how to play the game. <br />
        Update the instructions so that they're appropriate to whatever level the user is currently playing.</p3>
</body>

The script src lines are referencing the JS files I want to use, but when I view the page in a browser, I just get a blank canvas. Could someone point out to me what I'm doing wrong here? I'm not sure how I 'attach' the JS to the HTML when writing it in a separate file.

Edit 21/11/2012 at 12:00

Having made the changes suggested, I tried viewing the page in Firefox again, and in the Firebug console, when the page loaded, it said that there was an "unterminated regular expression literal in one of my JS files. The file it was complaining about contains this JS code:

    /* Create a canvas layer to display text */
    function displayText(textLayer, message){
        var textLayerContext = textLayer.getContext();
        textLayer.clear();
        textLayerContext.font = "18pt Calibri";
        textLayerContext.fillStyle = "black";
        textLayerContext.fillText(message, 10, 10);
    }
    
    /* Create a canvas layer to display the button */
    window.onload = function(){
        var stage = new Kinetic.Stage({
            container: "container",
            width: 179,
            height: 180
        });
        var buttonLayer = new Kinetic.Layer();
        var textLayer = new Kinetic.Layer();
    }
</script>

<script type="text/javascript">
/*Google analytics code for tracking website. */
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-31216545-1']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

and the line it was complaining about was the </script>

It does now work, but making this change doesn't seem to have improved performance much in terms of the time it takes to load an image after clicking the start button... any suggestions?


Solution

  • You're doing it right as is, it could be that your scripts are so big that it takes a while before it renders. The browser interprets the HTML top to down and when it encounters a javascript file it starts rendering that.

    In your case I would try to move the javascript files to the bottom of your page and try it again. Also, you have to make sure that the script files are loaded in the correct order.

    Also, you should place the <section></section> inside the body and not in the <head> and the <p> should have an id="#n" and last but not least a href on your image when wanting to use a javascript is invalid, use the onClick attribute instead :)

    Use the W3C validator service here to validate your HTML.

    To then use the functions that you want you "simply" put them either in your onLoad() or if you're keen on using jQuery you can do

    $(document).ready(function(){ //perform your functions as normal here });

    Have you tried debug your application in Firebug?