$.getScript(filePath,callbackFun)
getScript可以异步加载js文件,执行效果和本页的js是一样的
js模块是闭包的一种体现,模块里面的变量、函数与外面的变量、函数互不影响,如:
wsmodule = (function () {
let ws = null;
let conn = function (websocket_url) {
ws = new WebSocket('ws://' websocket_url);
ws.onopen = function () {
console.log("已经连接到服务器" websocket_url);
}
ws.onmessage = function (evt) {
console.log("收到消息:" evt.data);
let json = JSON.parse(evt.data);
if (json) {
switch (json.cmd) {
case "quit": //通知登出
{
if (json.uid != "-1") {
$.post('/Account/SignOutWithNotice', { uid: json.uid }, function (r) {
if (r == "ok") {
location = "/Account/SignOutOk";
}
});
}
}
break;
case "kicklogin": //账号踢出
$.post('/Account/SignOutWithKick', { sessionId: json.sessionId, uid: json.uid }, function (r) {
if (r == "ok") {
msg(msgshowType.error, "账号在别处登录,退出当前系统!");
setTimeout(() => {
location = "/Account/SignOutOk";
}, 3000);
}
});
break;
}
}
}
ws.onclose = function () {
console.log("客户端已断开连接");
};
ws.onerror = function (evt) {
console.log("发生错误:" evt.data);
};
return ws;
}
return {
conn: conn
};
})();
那么如何用getScript加载模块并调用呢?
$.getScript("/Scripts/wsmodule.js", function () {
let ws = wsmodule.conn("192.168.0.211"); //创建websocket连接
if (sso_session_id != "" && sso_user_id != "" && sso_session_id != "-1" && sso_user_id != "-1") {
setTimeout(() => {
//当前客户端登录了,广播其它客户端,其它地方登录的账号强制退出
let json = { cmd: "kicklogin", sessionId: sso_session_id, uid: sso_user_id };
ws.send(JSON.stringify(json));
}, 300);
}
});
可以看到getScript是相当灵活的,并不需要事先申明,随调随用!