Can I load javascript code using <link> tag?

前端 未结 8 1483
情歌与酒
情歌与酒 2020-12-02 20:20

Can I load javascript code using tag in my website ?

For example I have a javascript file, test.js, which contains the simple

相关标签:
8条回答
  • 2020-12-02 20:51

    Possible rationale why not

    • link elements are only allowed where "Metadata content" is allowed, typically head, and not in the body. See: Contexts in which this element can be used. All embedded elements that go in the body have separate elements for them: img, iframe, etc.

    • link elements must be empty, and script may be non-empty. See: Content model

    Therefore it is natural to have a separate element for JavaScript, and since we must have a separate element, it is better not to duplicate functionality with link rel="script".

    This theory also explains why img and style have separate elements:

    • img can be placed in the body, so it gets a separate element, even though it must be empty.

    • style can be non-empty, so it gets a separate element, even though until HTML5 it could not be placed in the body (now it can via scoped, but still not to include external scripts).

    0 讨论(0)
  • 2020-12-02 20:51

    The other option for this is, you can dynamically insert a script file into the current document, by creating a SCRIPT tag, setting its "src" attribute to the URI of the script, and then inserting it as a child of the page's HEAD node.

    Doing those things will get the browser to fetch the script file, load it into the document, and execute it.

    0 讨论(0)
  • 2020-12-02 20:58

    No. A Link tag like is for CSS files or for relational links (like next).

    This is not the way to load javascript into the page. You need to use the <script> tag:

    <script language="javascript" src="file.js" />
    
    0 讨论(0)
  • 2020-12-02 21:02

    You need to use the <script> tag to include JavaScript source files:

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

    The end tag must be the full </script>, don't abbreviate the way you can with some tags as in <script type="text/javascript" src="..."/>.

    Yes, alert statements in the included source will appear when they are evaluated by the browser.

    For information on the uses of the <link> tag, see w3.org.

    0 讨论(0)
  • 2020-12-02 21:06

    JavaScript code would generally be loaded using a script tag, like so:

    <script type="text/javascript" src="test.js"></script>
    
    0 讨论(0)
  • 2020-12-02 21:12

    No. There was a proposal to allow:

    <link rel="script" href=".../script.js"/>
    

    analogously to stylesheets. This is even quoted as an example in the HTML 4 DTD, but browser implementation never happened. Shame, as this would have been much cleaner.

    0 讨论(0)
提交回复
热议问题