Ways to add javascript files dynamically in a page

后端 未结 9 1650
盖世英雄少女心
盖世英雄少女心 2020-11-28 09:16

I have seen Scriptaculous.js file to include its required javascript files dynamically. Is there any better approach to include javascript dynamically.

For example,

9条回答
  •  天涯浪人
    2020-11-28 09:53

    document.getElementsByTagName("head")[0].appendChild(fileref‌​) is not working if you have some document.ready() works inline. $("head").append(fileref); works great for me, although it needs jquery.min.js inline reference.

    
        
        
        
        
    
    

    and master_load.js :

    function loadjscssfile(filename) {
        if (filename.substr(filename.length - 4) == ".css") { // 'endsWith' is not IE supported.
            var fileref = document.createElement("link")
            fileref.setAttribute("rel", "stylesheet")
            fileref.setAttribute("href", filename)
            //fileref.setAttribute("type", "text/css")
        }
        else if (filename.substr(filename.length - 3) == ".js") {
            var fileref = document.createElement('script')
            fileref.setAttribute("src", filename)
            //fileref.setAttribute("type", "text/javascript")
        }
        $("head").append(fileref);
    }
    function load_master_css() {
        loadjscssfile("css/bootstrap.min.css");
        // bunch of css files
    }
    function load_master_js() {
        loadjscssfile("script/bootstrap.min.js");
        // bunch of js files
    }
    

提交回复
热议问题