如何附加<脚本>头或身体使用Javascript

How to append <script> to Head or Body Using Javascript?

本文关键字:Javascript gt 何附加 lt 脚本      更新时间:2023-09-26

我有一个JavaScript问题。

我在谷歌上搜索了如何使用javascript进行附加,并找到了一个例子。我想手动将script标记附加到head或body,但该示例只是附加在head中。

我编辑了这个例子,这样脚本标记就可以附加在头或正文中,但代码不起作用。

有人能帮我解决问题吗?请给我看jsfiddle上的演示:D

谢谢:)

这里是我的脚本:

//JS
//Defined with  loadjscssfile("yourcssurl.js", "js", "head"); or addCss("yourcssurl.js", "js", "body");
//CSS
//Defined with  loadjscssfile("yourcssurl.css", "css", "head"); or addCss("yourcssurl.css", "css", "body");
function loadjscssfile(filename, filetype, pos) {
    if (filetype == "js") { //if filename is a external JavaScript file
        var fileref = document.createElement('script')
        fileref.setAttribute("type", "text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype == "css") { //if filename is an external CSS file
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref == filetype) {
        document.getElementsByTagName(pos)[0].appendChild(fileref)
    }
    else if (typeof fileref != "undefined") {
        document.getElementsByTagName("head")[0].appendChild(fileref)
    }
}
loadjscssfile("myscript.js", "js", "body") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js", "body") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css", "body") ////dynamically load and add this .css file

这是我编辑之前的原始脚本:动态加载外部JavaScript或CSS文件

抱歉我的英语不好:)

您可以从谷歌学习动态附加脚本

(function () {
    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);
})();

我不确定你最终要实现什么,但仔细看一下脚本,它是异步的。所以您不必担心资源加载的顺序。

在某些用例中,您可能需要控制脚本加载的顺序,您可以考虑使用RequireJS或Modernizr

您非常接近,但您不需要添加额外的if条件,这应该足够了:

function loadjscssfile(filename, filetype, pos) {
    var fileref;
    if (filetype === "js") { //if filename is a external JavaScript file
        fileref = document.createElement("script");
        fileref.setAttribute("type", "text/javascript");
        fileref.setAttribute("src", filename);
    }
    else if (filetype === "css") { //if filename is an external CSS file
        fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }
    if (fileref) {
        document.getElementsByTagName(pos)[0].appendChild(fileref);
    }
}

试试看。