簡體   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