简体   繁体   中英

How can I include more than one Javascript file?

I want to use more Javascript files on one canvas, but I can't connect them. For example I want to write a Javascript file that contains all functions and an other Javascript file which is using them.

Show me a guide, how can I make this connection?

Thanks.

This is the first javascript file :

var canvas = null;
var ctx = null;

window.onload = function () {
    canvas = document.getElementById('myCanvas');
    ctx = canvas.getContext('2d');

    line (100,100,300,300);
}

This is the secnond file:

function line (x1,y1,x2,y2) {
    ctx.beginPath();
    ctx.moveTo(x1,y1);
    ctx.lineTo(x2,y2);
    ctx.stroke();
}

And this is my html file:

<!DOCTYPE html>

<html>
<head>
    <title>Tutorialok</title>
    <script type="text/javascript" src="CanvasElement.js"></script>
    <script type="text/javascript" src="line.js"></script>
    <style>
        #myCanvas {
            border: 1px solid #9C9898;
        }
    </style>
</head>

<body>
    <canvas id="myCanvas" width="800" height="600">
        Sorry your browser Does not support canvas element!
    </canvas>

</body>
</html>

The first file cant find the second files function.

Use namespacing via Objects . I don't recommend a pattern where all functions exist in one file, but this is an idea you could use. You MUST load file1.js before file2.js can do anything.

// file1.js
window.namespace = window.namespace || {};

window.namespace.fns = {
    foo: function () {}
};

// file2.js
window.namespace.fns.foo();

jsFile 1

var f1 = function(){};
var f2 = function(){}

jsFile2

 var s1 = f1();
 var s2 = f2();

use this on the html page

<script src="path/jsFile1.js"></script>
<script src="path/jsFile2.js"></script>

If you're expecting the function to hoist, I don't believe that would work between script files since each one is evaluated independently. Switch the script tags around so line is in scope when CanvasElement.js loads.

Otherwise, the global namespace is shared between the linked scripts.

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