javascript中動態載入js檔案多種解決辦法

來源:互聯網
上載者:User

一個比較全部在動態加方法

 代碼如下 複製代碼
/*
    動態載入js v1.0 by:dum 2012-03-17 www.111cn.net
    用法:src="webJsBase.js?load=a,b"
    註:載入本目錄下js
*/
var webJsBase = {
    require: function(libraryName) {
        document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
    },
    load: function(defaultLoad) {
        if((typeof Prototype=='undefined')||(typeof Element == 'undefined')||(typeof Element.Methods=='undefined'))
        throw ('prototype lib 載入失敗!');
        if(typeof defaultLoad=='undefined')defaultLoad='';
        var js = /webJsBase.js(?.*)?$/;
        $$('head script[src]').findAll(function(s) {
            return s.src.match(js);
        }).each(function(s) {
            var path = s.src.replace(js, '');
            var includes = s.src.match(/?.*load=([a-zA-Z0-9_,]*)/);
            (includes ? includes[1] : defaultLoad).split(',').each(function(include) {
                webJsBase.require(path + include + '.js');
            });
        });
    }
};

webJsBase.load(); //這裡參數可以指定預設要載入的js檔案

這是最簡單的方法在載入完後再利用直接document.write 如下圖。

 代碼如下 複製代碼

<script language="javascript">

    document.write("<script src='test.js'></script>");

</script>

給script加個id再去動態改變已有script的src 屬性

 代碼如下 複製代碼

<script src='' id="s1"></script>

<script language="javascript">

    s1.src="test.js"

</script>

這裡利用getElementsByTagName('HEAD')動態建立 script元素

 代碼如下 複製代碼

<script>

    var oHead = document.getElementsByTagName('HEAD').item(0);

    var oScript= document.createElement("script");

    oScript.type = "text/javascript";

    oScript.src="test.js";

    oHead.appendChild( oScript);

</script>

還可以這樣嘗試一下,自定一個函數

 

 代碼如下 複製代碼
function include(src) {
HTMLCode = '<script language="javascript" src="' + src + '"></script>';
document.write(HTMLCode);
}

調用方法,這樣看上去就你php的include函數了

 代碼如下 複製代碼


include(baseDir + "/Prototype.js");
include(baseDir + "/Map.js");
include(baseDir + "/MapEvent.js");

include(baseDir + "/model/MapModel.js");
include(baseDir + "/model/MapType.js");
include(baseDir + "/model/Tile.js");

還有朋友說可以使用ExtJs4 動態載入js這裡我就不介紹了,上面的方法足夠讓你實現動態載入js了.

所以在採用這類方法動態載入Js 的同時,主介面的Js指令碼是繼續執行的,所以可能出現通過非同步載入的Js代碼得不到預期的效果的情況。

這時候可以考慮採用Ajax載入Js的方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.