对于我正在编写的这个用户脚本,我需要使用包含3个JavaScript文件的第三方JavaScript库。由于@require无法在Chrome上运行,如何向用户脚本添加多个外部JavaScript库?在选择之前我正在考虑所有可能性。
我知道你可以使用this方法添加jQuery。我亲自使用过它。是否可以使用此解决方法添加其他库?
答案 0 :(得分:3)
尝试在用户脚本中添加以下功能
/**
* 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)
}
由于文件是异步加载的,并且无法保证加载文件的顺序 对于多个外部文件,在一个chined函数中调用此函数,例如
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.
});
});
根据需要链接尽可能多的外部文件,将正确保存加载文件的顺序。希望这会有所帮助,一切顺利
答案 1 :(得分:1)
虽然其他答案也会有效,但我需要更多的灵活性。这是我想出的版本:http://userscripts.org/scripts/show/123588
答案 2 :(得分:0)
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);