javascript - 包括 javascripts 不工作

标签 javascript jquery

我发现了一个小的 javascript 片段,用于仅在之前未包含的情况下包含 javascript。

这是使用我自己的脚本,但使用两个第三方库时它不起作用,我真的不知道为什么。

    var included_files = new Array();
    function include_once(script_filename) {
        if (!in_array(script_filename, included_files)) {
            included_files[included_files.length] = script_filename;
            include_dom(script_filename);
        }
    }
    function in_array(needle, haystack) {
        for (var i = 0; i < haystack.length; i++) {
            if (haystack[i] == needle) {
                return true;
            }
        }
        return false;
    }
    function include_dom(script_filename) {
        var html_doc = document.getElementsByTagName('head').item(0);
        var js = document.createElement('script');
        js.setAttribute('language', 'javascript');
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', script_filename);
        html_doc.appendChild(js);
        return false;
    }

function loaded() {
    include_once("shared/scripts/jquery.min.js");
    include_once("shared/scripts/iscroll.js");

    $(document).ready(function () {
        alert("hello");
    });
}

错误:$ 未定义。 如果我以常规方式导入 jQuery,它会显示“iScroll”未定义(因为我稍后会使用它)。

有什么想法吗?

最佳答案

include_dom 是异步的。它并行加载脚本,您无法真正确定何时加载脚本。您尝试在开始下载后立即使用 jQuery,但这不起作用。

您需要使用允许您为加载的脚本指定回调的脚本。我会推荐 require.js

关于javascript - 包括 javascripts 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12969622/

相关文章:

php - 检查我的页面是否嵌入到 iframe 中

javascript - 使用 jQuery 对数组中的值求和

javascript - 在页面上拖放文件时如何设置文件输入值?

javascript - Yii2:基于条件使用JQuery计算

javascript - Angular JS ng-repeat 从数组中选择随机分组?

javascript - 折叠/展开时动画字体 Awesome Chevron 图标旋转

javascript - jQuery 每个函数都不起作用并且无法创建 json 字符串

jquery - Kendo UI 网格绑定(bind)两次

javascript - 如何在 w2ui 中使布局小部件扩展到完整高度?

javascript - Htaccess URL 重写的异常行为