Search code examples
javascriptonload

Why external JS won't start?


after to make some research I took the measures to guarantee that the JS will be loaded before trying to run it but... it won't work!

This works:

<!DOCTYPE html>
<head>
    <meta name="viewport" content="initial-scale=1" charset="utf-8">
</head>
<html>
    <body>
    <script type="text/javascript">
        function initialize() {
            console.log('foo')
        }

        window.onload = function() {
            initialize();
        };
    </script>
</body>
</html>

But this doesn't:

<!DOCTYPE html>
<head>
    <meta name="viewport" content="initial-scale=1" charset="utf-8">
</head>
<html>
    <body>
    <script type="text/javascript" src="test.js">
    <script type="text/javascript">
        window.onload = function() {
            initialize();
        };
    </script>
</body>
</html>

test.js:

function initialize() {
    console.log('foo')
}

I don't get any error. It just doesn't work. What am I doing wrong?

Thanks!


Solution

  • You need a closing script tag for the tag that is calling the external js file.

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