如何包含外部JS文件,而不包括在头部标签

How to include external JS files without including them in the head tag?

本文关键字:不包括 头部 标签 何包含 外部 JS 文件      更新时间:2023-09-26

我将按照本教程创建一个选项卡视图。可以看到,我们在<head>部分中包含了四个外部JS文件

<script type="text/javascript" src="http://yui.yahooapis.com/2.5.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
    <script type="text/javascript" src="http://yui.yahooapis.com/2.5.0/build/element/element-beta-min.js"></script>
    <script type="text/javascript" src="http://yui.yahooapis.com/2.5.0/build/connection/connection-min.js"></script>
    <script type="text/javascript" src="http://yui.yahooapis.com/2.5.0/build/tabview/tabview-min.js"></script>

那么在<body>中,唯一与制表符有关的JS代码是

<script type="text/javascript">
    var myTabs = new YAHOO.widget.TabView("content-explorer");
</script>

问题:-

由于某种原因,我不能在<head>标签中放入任何代码。那么我是否可以在 var myTabs = new YAHOO.widget.TabView("content-explorer");之前将external JS files包含在JS代码中呢?

有几种方法可以做到这一点,但最简单的是在JavaScript中创建一个script元素,并在运行时将其附加到文档中。

为简单起见,我在这里的循环中完成了此操作,以容纳要包含的脚本数量;resources是一个字符串数组,包含指向资源位置的url:

<script>
    //array of scripts to include
    var resources = ["http://yui.yahooapis.com/2.5.0/build/yahoo-dom-event/yahoo-dom-event.js", "http://yui.yahooapis.com/2.5.0/build/element/element-beta-min.js", "http://yui.yahooapis.com/2.5.0/build/connection/connection-min.js", "http://yui.yahooapis.com/2.5.0/build/tabview/tabview-min.js"];
    for(var i = 0; i < resources.length; i++){
        var script = document.createElement("script");
        script.setAttribute("type", "text/javascript");
        script.setAttribute("src", resources[i]);
        document.getElementsByTagName("head")[0].appendChild(script);
    }
    //stuff to do after scripts have loaded
    var myTabs = new YAHOO.widget.TabView("content-explorer");
</script>