tags:

views:

105

answers:

4

I have this script in the 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"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;

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

Final result is that the text "Hello silly world!" is 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. Thanks.

+16  A: 

I think the src tag overrides whatever's inside.

Try the following:

    <script type="text/javascript" src="JavaScript/Sample.js"></script>
    <script type="text/javascript">
        MyPrint("Hello silly world!");
    </script>
Tim Čas
That's the one. You can have code or `src`, but not both.
Kobi
Well, replace `JavaScript/Sample.js` with whatever the script is, then replace the `MyPrint(...)` call with the function.
Tim Čas
well done! thank you very much.
Boris
I believe that the type attribute is not needed.
Šime Vidas
@Sime Vidas, it's not needed on html5
Sinan Y.
@Sinan OK, it is needed for validation. I meant that it is not needed in order for the JavaScript to execute properly in todays browers (regardless of the used DOCTYPE)
Šime Vidas
@Sinan The type attribute gets ignored in nearly all browsers
indieinvader
I think it's good practice to preserve the type anyways. Just my 2 cents.
Tim Čas
John Resig wrote a pretty interesting blog post about this exactly. ["Degrading Script Tags"](http://ejohn.org/blog/degrading-script-tags/) deals with allowing something like `<script src='myscript.js'>code();</script>`. Give it a read!
clarkf
I'm *guessing* it's the other way around than what you describe it - the internal script is ran on error (as in, when, say, the external script is missing)?
Tim Čas
A: 
window.onload = function(){
 MyPrint("Hello silly world!");
};
Misiur
The script uses `document.write` so this will not have the desired behaviour.
David Dorward
+3  A: 

Your script can be considered loaded after the closing </script> element. 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>
The MYYN
A: 
<script type="text/javascript">
MyPrint("Hello silly world!");
</script>
conrad