简体   繁体   中英

Coding inside script tags that load external js files

I did a random experiment and tried to do write inside script tag that loads external js files and call one of the methods and it didn't work. This is my js file

//external.js
var myObject = {
    myMethod: function(){
        document.getElementById('container').innerHTML = "Hello, Internet!"
    }
}

Here is the html:

<script type="text/javascript" src="external.js">
    myObject.myMethod();
</script>

So I have two questions. One is obviously why didn't the method get called? Second is why were there no errors in my console? eg: myObject.myMethod is not a function

Code within <script src="–"> elements that reference files via the src attribute does not get executed . This is explained in Restrictions for contents of script elements , but no browser "enforces" the "must be comment content" thing.

Identifying the current <script> element explains how this behavior can be used to parameterize script execution.

Take a look here https://www.w3.org/TR/html4/interact/scripts.html#h-18.2.1

The script may be defined within the contents of the SCRIPT element or in an external file. If the src attribute is not set, user agents must interpret the contents of the element as the script. If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI. Note that the charset attribute refers to the character encoding of the script designated by the src attribute; it does not concern the content of the SCRIPT element.

Put the function call in your external JavaScript file like so:

var myObject = {
    myMethod: function(){
        document.getElementById('container').innerHTML = "Hello, Internet!"
    }
}

myObject.myMethod();

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