The simplest JavaScript in the world will not work!

I have this script in a separate Sample.js file:

function MyPrint(text)
{
 document.write(text);
}

And I have the following HTML page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>Silly example</title>
</head>
<body>
    <div>
        <script type="text/javascript" src="JavaScript/Sample.js">
            MyPrint("Hello silly world!");
        </script>
    </div>
</body>
</html>

The end result is that the text "Hello, stupid world!" NOT printed on the page. What should I do to make this work? I would prefer not to move the script tag to the head if possible. Thank you

+3
source share
4 answers

I think the src tag overrides everything inside.

Try the following:

    <script type="text/javascript" src="JavaScript/Sample.js"></script>
    <script type="text/javascript">
        MyPrint("Hello silly world!");
    </script>
+18
source

Your script can be considered loaded after the closing element </script>. This should work:

<!-- just a sidenote: type="text/javascript" is the default for script as of html5 -->
<script src="JavaScript/Sample.js"></script>
<script>MyPrint("Hello silly world!");</script>
+4
source
<script type="text/javascript">
MyPrint("Hello silly world!");
</script>
0
window.onload = function(){
 MyPrint("Hello silly world!");
};
-1

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


All Articles