动态加载Mui类库:
// ==UserScript==
// @name
// @version 1.4.0
// @author zzdhidden@gmail.com
// @namespace https://github.com/zzdhidden
// @description 异步加载mui类库
// @include
// @require
// ==/UserScript==
function withMUI(callback, safe){
if(typeof(mui) == "undefined") {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "${resModel.getJsDomain()}/communal/static/js/mui.js";
if(safe) {
var cb = document.createElement("script");
cb.type = "text/javascript";
cb.textContent = "(" + callback.toString() + ")(mui, window);";
script.addEventListener('load', function() {
document.head.appendChild(cb);
});
}
else {
var dollar = undefined;
if(typeof($) != "undefined") dollar = $;
script.addEventListener('load', function() {
$ = dollar;
callback(mui, window);
});
}
document.head.appendChild(script);
} else {
setTimeout(function() {
//Firefox supports
callback(mui, typeof unsafeWindow === "undefined" ? window : unsafeWindow);
}, 30);
}
}
withMUI(function($, window){
$(function() {
//在此就可以执行执行你的代码了
})();
}, true);
核心是要script的load事件完成后执行代码才有效。
动态加载jquery:
// ==UserScript==
// @name 12306 Booking Assistant
// @version 1.4.0
// @author zzdhidden@gmail.com
// @namespace https://github.com/zzdhidden
// @description 12306 订票助手之(自动登录,自动查票,自动订单)
// @include *://dynamic.12306.cn/otsweb/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==
function withjQuery(callback, safe){
if(typeof(jQuery) == "undefined") {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
if(safe) {
var cb = document.createElement("script");
cb.type = "text/javascript";
cb.textContent = "jQuery.noConflict();(" + callback.toString() + ")(jQuery, window);";
script.addEventListener('load', function() {
document.head.appendChild(cb);
});
}
else {
var dollar = undefined;
if(typeof($) != "undefined") dollar = $;
script.addEventListener('load', function() {
jQuery.noConflict();
$ = dollar;
callback(jQuery, window);
});
}
document.head.appendChild(script);
} else {
setTimeout(function() {
//Firefox supports
callback(jQuery, typeof unsafeWindow === "undefined" ? window : unsafeWindow);
}, 30);
}
}
withjQuery(function($, window){
$(function() { alert("jQuery loaded"); })();
}, true);