简体   繁体   中英

Why can't I execute JavaScript function inside the <script> tag that defines the .js source?

I am defining the source of a .js file and attempting to call a function from that file in the same tag, as follows:

<script type="text/javascript" src="jsFunctionTest.js">
    testMethodCall();
</script>

The .js file just contains:

function testMethodCall(){
    window.alert("Hello there");
}

This doesn't work, I don't see the alert.

However, if I change the tag to two tags, as below, then it works:

<script type="text/javascript" src="jsFunctionTest.js"></script>
<script type="text/javascript">
    testMethodCall();
</script>

This seems pretty messy. Is there any reason the first one doesn't work?

script elements can have a src attribute or content, but not both. If they have both, the content is ignored (the content is considered "script documentation," not code).

You cannot register an external file and use the content in it, both at a time inside <script> tags. Only either one is allowed.

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