JavaScript - 需要加载外部 JS 文件的功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8278492/
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-10-26 02:53:28  来源:igfitidea点击:

JavaScript - function to load external JS files is needed

javascript

提问by Ron

Recently I added to my website facebook like button, twitter follow us button and google +1 button. I want their JS scripts to load when I tell them to load.

最近我在我的网站上添加了 facebook like 按钮、twitter 关注我们按钮和 google +1 按钮。当我告诉他们加载时,我希望他们的 JS 脚本加载。

Therefore, I need a function that load external JS files. I don't need to know when the file finished to load (callback is not needed).

因此,我需要一个加载外部 JS 文件的函数。我不需要知道文件何时完成加载(不需要回调)。

I found some methods/functions on the Internet, but I want to know which would be the best choice for this situation?

我在互联网上找到了一些方法/功能,但我想知道哪种方法是这种情况的最佳选择?

4 ways to dynamically load external JavaScript
Dynamically loading JS libraries and detecting when they're loaded
The best way to load external JavaScript

动态加载外部 JavaScript 的 4 种方法
动态加载 JS 库并检测它们何时加载
加载外部 JavaScript 的最佳方法

Thanks.

谢谢。

Edit: Added the methods/function I found.

编辑:添加了我找到的方法/功能。

采纳答案by Sudhir Bastakoti

This might be helpful:

这可能会有所帮助:

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

回答by florianletsch

I would recommend using jQuery's getScript(). For the twitter-button, you would load the corresponding script like that:

我建议使用 jQuery 的 getScript()。对于 twitter 按钮,您可以像这样加载相应的脚本:

$.getScript("//platform.twitter.com/widgets.js")

Of course you would have to load jqueryin your script first and do not forget to add the markup needed for the twitter-buttonin your html.

当然,您必须首先在脚本中加载 jquery,并且不要忘记在 html 中添加twitter-button 所需标记

回答by Madara's Ghost

Something like

就像是

function getScript(url) {
    e = document.createElement('script');
    e.src = url;
    document.body.appendChild(e);
}
getScript('jstoload.js');

this?

这?

回答by Zoidberg

The YUI Loadersounds like a good choice for you. It will also allow you to add your own custom modules, so you can load on demand, as well as load all other JS files that are required as well.

YUI加载听起来是个不错的选择。。它还允许您添加自己的自定义模块,以便您可以按需加载,以及加载所有其他需要的 JS 文件。