Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

html - Run JavaScript inside <script src="..."></script> Tags?

I've a JavaScript file that processes tab switches. Here is the source:

var tCount = 0;

function SwitchToTab(id) {
    if (id < 0 || id > tCount) { id = 0; }

    for (var i = 0; i < tCount; i++) { document.getElementById("tab" + i).className = ""; }
    document.getElementById("tab" + id).className = "active";

    for (var i = 0; i < tCount; i++) { document.getElementById("area" + i).style.display = "none"; }
    document.getElementById("area" + id).style.display = "";
}

function InitializeTabs(initialTabId, tabsCount) {
    tCount = tabsCount;
    SwitchToTab(initialTabId);
}

I'm trying to make it as short as possible like this:

<script src="Resources/Tabs.js">InitializeTabs(0, 4);</script>

It doesn't works but it works if I separate them like this:

<script src="Resources/Tabs.js"></script>
<script>InitializeTabs(0, 4);</script>

So, is there any way to run JavaScript inside <script src="..."></script> tags? What I am missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, this is not possible. The html spec dictates that a <script> tag does one or the other.

W3 Schools, emphasis mine.

The element either contains scripting statements, or it points to an external script file through the src attribute.

Note: If the "src" attribute is present, the element must be empty.

<script>Tag Html Spec, emphasis mine.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...