简体   繁体   English

如何包含外部JS文件而不将它们包含在head标签中?

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

I am following this tutorial to create a tabbed view . 我正在按照本教程创建选项卡式视图 As we can see, we have included four external JS files in the <head> section. 如我们所见,我们在<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>

Then in the <body> , the only JS code concerned with the tabs is 然后在<body> ,与选项卡有关的唯一JS代码是

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

QUESTION:- 题:-

Due to some reason, I can not put any code in the <head> tag. 由于某些原因,我无法在<head>标记中放入任何代码。 So is there any way I can include the external JS files in the JS code before var myTabs = new YAHOO.widget.TabView("content-explorer"); 所以有什么办法可以 var myTabs = new YAHOO.widget.TabView("content-explorer"); 之前JS代码中包含external JS files var myTabs = new YAHOO.widget.TabView("content-explorer"); ?

There are a couple of ways to do it, but the easiest is to create a script element in JavaScript and append it to the document when it runs. 有两种方法可以做到这一点,但最简单的方法是在JavaScript中创建script元素,并在运行时将其附加到文档中。

For simplicity, I've done this in a loop here to accommodate the number of scripts to include; 为简单起见,我在此处循环执行了此操作,以容纳要包含的脚本数量。 resources is an array of strings that contain URLs pointing to the resources' locations: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM