Javascript 在页面中动态添加javascript文件的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5751620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:42:04  来源:igfitidea点击:

Ways to add javascript files dynamically in a page

javascriptjqueryprototypejsscriptaculous

提问by Nazmul

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

我已经看到 Scriptaculous.js 文件动态包含其所需的 javascript 文件。有没有更好的方法来动态包含 javascript。

For example, I would like to include my js files like,

例如,我想包含我的 js 文件,例如,

<script src="single.js?files=first.js,second.js,third.js..."></script>

How can I do that in an efficient manner?

我怎样才能以有效的方式做到这一点?

回答by Anand Thangappan

To load a .js or .css file dynamically, in a nutshell, it means using DOM methods to first create a swanky new "SCRIPT" or "LINK" element, assign it the appropriate attributes, and finally, use element.appendChild() to add the element to the desired location within the document tree. It sounds a lot more fancy than it really is. Lets see how it all comes together:

要动态加载 .js 或 .css 文件,简而言之,这意味着使用 DOM 方法首先创建一个时髦的新“SCRIPT”或“LINK”元素,为其分配适当的属性,最后使用 element.appendChild()将元素添加到文档树中的所需位置。这听起来比实际情况要花哨得多。让我们看看这一切是如何结合在一起的:

function loadjscssfile(filename, filetype){
 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!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

i hope its use full

我希望它充分利用

回答by Vivek

You can use the jQuery.getScript()function... I think it will be much easier to you with this to include a JavaScript .jsfile.

您可以使用该jQuery.getScript()功能...我认为通过此功能包含一个 JavaScript.js文件对您来说会容易得多。

Hereis the reference.

是参考。

回答by herostwist

there are many different ways, but the way Google loads additional scripts is like this:

有很多不同的方式,但谷歌加载额外脚本的方式是这样的:

function getScript(src) {
    document.write('<' + 'script src="' + src + '"' +
                   ' type="text/javascript"><' + '/script>');
}

This is taken directly from Google maps loader.

这是直接从谷歌地图加载器中获取的。

Writing a script tag directly to the document is the simplest and most efficient way.

将脚本标签直接写入文档是最简单、最有效的方式。

回答by Luke

Following the advice of Salaman A's comments, I found how Google does it now with Analytics: https://developers.google.com/analytics/devguides/collection/gajs/asyncTracking

按照Salaman A 的意见建议,我发现了 Google 现在如何使用 Analytics:https: //developers.google.com/analytics/devguides/collection/gajs/asyncTracking

And here is a more generic version of the same code:

这是相同代码的更通用版本:

(function() {
    var s = document.createElement('script'); // Create a script element
    s.type = "text/javascript";               // optional in html5
    s.async = true;                           // asynchronous? true/false
    s.src = "//example.com/your_script.js"; 
    var fs = document.getElementsByTagName('script')[0];  // Get the first script
    fs.parentNode.insertBefore(s, fs);
})();

回答by AmirHossein Manian

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.jsinline reference.

document.getElementsByTagName("head")[0].appendChild(fileref??)如果您有一些 document.ready() 内联工作,则不起作用。$("head").append(fileref);对我很有用,虽然它需要jquery.min.js内联参考。

<head>
    <!-- Meta, title, CSS, favicons, etc. -->
    <script src="script/jquery.min.js"></script>
    <script src="script/master_load.js"></script>
    <script>
        load_master_css();
        load_master_js();
    </script>
</head>

and master_load.js:

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
}

回答by Salman A

I've seen what the scriptaculous loader does. What it does is that it goes through all script tags in the document to find the one that loaded itself, e.g:

我已经看到了 scriptaculous 加载器的作用。它的作用是遍历文档中的所有脚本标签以找到自己加载的那个,例如:

<script src="/path/to/single.js?files=first.js,second.js,third.js"></script>

Then it parses the querystring used inside the src attribute and dynamically create additional script tags for each script file. At the same time it also parses the path of the base script (/path/to/single.js) and uses the same path to load dependency files (e.g. /path/to/first.js).

然后它解析 src 属性中使用的查询字符串,并为每个脚本文件动态创建额外的脚本标签。同时它也解析基础脚本的路径(/path/to/single.js)并使用相同的路径加载依赖文件(例如/path/to/first.js)。

You can create your own script loader like this. In vanilla javascript, you can use the following functions:

您可以像这样创建自己的脚本加载器。在 vanilla javascript 中,您可以使用以下函数:

Anand Thangappan has posted a solution that uses these functions. If you're using a framework such as jQuery or MooTools then both provide their own implementations of dynamically loading JsvaScript.

Anand Thangappan 发布了一个使用这些功能的解决方案。如果您使用的是 jQuery 或 MooTools 等框架,那么两者都提供了自己的动态加载 JsvaScript 实现。

Finally, there is a server side solution for your problem. Look at minify-- Combines and minifies multiple CSS or JavaScript files into a single download.

最后,您的问题有一个服务器端解决方案。查看minify -- 将多个 CSS 或 JavaScript 文件合并并缩小到单个下载中。

回答by Justin808

To add a new javascript file dynamically:

动态添加新的 javascript 文件:

function includeJS(jsFile) {
    $('head').append($('<script>').attr('type', 'text/javascript').attr('src', jsFile));
}


// Pick a JS to load
if ($.browser.msie) {
    includeJS('first.js');
} else {
    includeJS('second.js');
}
includeJS('third.js');

回答by Dennis Bartlett

We can quickly extend this so that a callback can be performed once the script is added.

我们可以快速扩展它,以便在添加脚本后可以执行回调。

function loadjscssfile(filename, filetype, callback){
    if (typeof fileref!="undefined") {
        document.getElementsByTagName("head")[0].appendChild(fileref);
        callback();
    }
}