DOM & JavaScript - When is the right time to create a JavaScript file?

I work on a simple page that uses only <canvas>within the <body>page. All content is loaded through javascript. I was having problems using a document in my javascript and I was wondering if anyone could point me in the right direction of using tags <script>. Here is my main question:

  • What is the appropriate location <script>for a function loaded with window.onload

Here is the code I'm working with:

index.html
----
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <script src="window.js" type="text/javascript"></script>
    </head>
    <body>
        <canvas>Canvas is not supported by your browser!</canvas>
    </body>

window.js
----
Window = function(doc, win)
{
    this.doc = doc;
    this.win = win;

    this.initialize();
}

Window.prototype = 
{
    initialize: function()
    {
        this.doc.documentElement.style.overflow = 'hidden';
        this.doc.body.scroll = "no";

        this.resize();
        this.win.addEventListener('resize', this.resize.bind(this));
    },
    resize: function()
    {
        _canvas = this.doc.querySelector('canvas');
        _canvas.width = this.win.innerWidth;
        _canvas.height = this.win.innerHeight;

    }
};

window.onload = new Window(document, window);

In all tests of this script I ran, the only instance where it works is when it <script>is placed after the start tag <body>. When I put <script>in <head>, this leads to an error:

Uncaught TypeError: Cannot set property 'value' of null

, , , <script> <head>?

, , !

+4
3

Script . , ...

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <canvas>Canvas is not supported by your browser!</canvas>

        <script src="window.js" type="text/javascript"></script>
    </body>
</html>
+2

, JS. , JS , DOM . , JS , . JS -, , DOM . jQuery ready

$(document).ready(function() { alert('My DOM is loaded!'); });

jQuery DOMContentLoaded. window.js, .

document.addEventListener("DOMContentLoaded", function(event) {
    new Window(document, window);
});
0

If you do not put the script in the after element, as far as your script is, this element does not exist. It should be at the bottom, or at least after the canvas element.

In your case, it should be at the bottom, after the element <canvas>.

0
source

Source: https://habr.com/ru/post/1523564/


All Articles