繁体   English   中英

如何在用户脚本中集成第三方JavaScript库

[英]how to integrate third-party JavaScript libraries in userscripts

对于我正在编写的这个用户脚本,我需要使用包含3个JavaScript文件的第三方JavaScript库。 由于@require无法在Chrome上运行,如何向用户脚本添加多个外部JavaScript库? 在选择之前我正在考虑所有的可能性。

我知道你可以使用这种方法添加jQuery。 我亲自使用过它。 是否可以使用此解决方法添加其他库?

尝试在用户脚本中添加以下功能,

/**
 * Dynamically loading javascript files.
 *
 * @param filename url of the file
 * @param callback callback function, called when file is downloaded and ready
 */
function loadjscssfile(filename, callback) {
    var fileref = document.createElement('script')
    fileref.setAttribute("type", "text/javascript")
    fileref.setAttribute("src", filename)
    if (fileref.readyState) {
        fileref.onreadystatechange = function() { /*IE*/
            if (fileref.readyState == "loaded" || fileref.readyState == "complete") {
                fileref.onreadystatechange = null;
                callback();
            }
        }
    } else {
        fileref.onload = function() {  /*Other browsers*/
            callback();
        }
    }

    // Try to find the head, otherwise default to the documentElement
    if (typeof fileref != "undefined")
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(fileref)
}

由于文件是异步加载的,并且无法保证文件加载的顺序,而不是多个外部文件的顺序,所以在一个已知的函数中调用此函数,例如

loadjscssfile("http://code.jquery.com/jquery-1.6.3.min.js", function() {
    loadjscssfile("http://www.abc.org./script/otherFile.js", function() {
       // call your function that depends on the external libriries here.
     });
});

根据需要链接尽可能多的外部文件,将正确保存加载文件的顺序。 希望这有所帮助,一切顺利

虽然其他答案也可以,但我需要更多的灵活性。 这是我想出的版本: http//userscripts.org/scripts/show/123588

function requireFiles(jsLibs, callback) 
{
    //array to hold the external libabry paths
    var jsLibs = new Array();
    jsLibs[0] = "http://code.jquery.com/jquery-1.7.1.min.js"
    jsLibs[1] = "https://raw.github.com/gildas-lormeau/zip.js/master/WebContent/zip.js"
    jsLibs[2] = "https://raw.github.com/gildas-lormeau/zip.js/master/WebContent/deflate.js"
    jsLibs[3] = "https://raw.github.com/gildas-lormeau/zip.js/master/WebContent/inflate.js"

    var index = 0;
    var requireNext = function() 
    {
        var script = document.createElement("script");
        if (index < jsLibs.length) 
        {
            script.addEventListener("load", requireNext, false);
            script.setAttribute("src", jsLibs[index++]);
        }
        else 
        {
            script.textContent = "(" + callback.toString() + ")()";
        }
        document.body.appendChild(script);
    }
    requireNext();
}


function otherCode()
{
    //rest of the script
}

requireFiles(otherCode);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM