【问题标题】:How to call function when async Javascript file is loaded?加载异步Javascript文件时如何调用函数?
【发布时间】:2014-01-13 12:26:42
【问题描述】:

在我的网站上包含/加载第 3 方小部件后,我在调用函数时遇到了一点问题。

考虑这种情况。 我加载了一个脚本,它会像这样从 3rd 方库生成小部件。

<script>
var element= document.createElement("script");
element.src = 'http://example.com/script.js';
document.body.appendChild(element);
</script>

加载完成后创建#someElement div标签,该标签具有style属性和一些规则,并将其附加到body元素。

我想要做的是删除 style 属性并添加一些 CSS 类。

所以,问题是,我如何检查该文件何时加载,或者该元素何时创建并在此之后调用我的函数?

谢谢!

【问题讨论】:

    标签: javascript jquery asynchronous load


    【解决方案1】:

    检查脚本是否已加载:

    如果脚本在全局空间中创建了任何变量或函数,您可以检查它们是否存在:

    外部 JS(在全局范围内)--

    var myCustomFlag = true;
    

    并检查它是否已经运行:

    if (typeof window.myCustomFlag == 'undefined') {
        //the flag was not found, so the code has not run
        $.getScript('<external JS>');
    }
    

    您可以通过选择所有元素并检查它们的 src 属性来检查相关标签的存在:

    //get the number of `<script>` elements that have the correct `src` attribute
    var len = $('script').filter(function () {
        return ($(this).attr('src') == '<external JS>');
    }).length;
    
    //if there are no scripts that match, the load it
    if (len === 0) {
        $.getScript('<external JS>');
    }Or you can just bake this .filter() functionality right into the selector:
    
    var len = $('script[src="<external JS>"]').length;
    

    进一步讨论。见:Verify External Script Is Loaded

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      相关资源
      最近更新 更多