Add File
This commit is contained in:
97
main/ui/js/alp_unit.js
Normal file
97
main/ui/js/alp_unit.js
Normal file
@@ -0,0 +1,97 @@
|
||||
/** 实现了对AplpineJS模块的动态加载和模块的初始化 */
|
||||
|
||||
// 模块的cache,减少对服务器的访问次数
|
||||
var units_cache=new Map();
|
||||
|
||||
// 模块初始化
|
||||
var units_dom_init = new Map();
|
||||
|
||||
//装载单个uit
|
||||
function load_unit(matche,reinit){
|
||||
let unit_src = matche.getAttribute("alp-unit");
|
||||
|
||||
if (unit_src==null) return
|
||||
|
||||
//cache中存在,不用再此网络加载
|
||||
if (units_cache.has(unit_src)) {
|
||||
|
||||
if (!units_dom_init.has(matche)){
|
||||
|
||||
//未被初始化,则初始化
|
||||
matche.innerHTML=units_cache.get(unit_src);
|
||||
}else if(reinit){
|
||||
//强制重新初始化渲染
|
||||
matche.innerHTML=units_cache.get(unit_src);
|
||||
}
|
||||
|
||||
|
||||
}else{
|
||||
|
||||
var xhr = new XMLHttpRequest();
|
||||
xhr.onreadystatechange = function () {
|
||||
if (xhr.readyState == 4 && xhr.status == 200) {
|
||||
|
||||
var text = xhr.responseText.split("<script>");
|
||||
|
||||
//先设置html的Dom
|
||||
matche.innerHTML = text[0];
|
||||
|
||||
|
||||
//再启用函数
|
||||
if (text.length==2){
|
||||
var script=document.createElement("script");
|
||||
script.type="text/javascript";
|
||||
script.text=text[1].slice(0,-11);
|
||||
document.getElementsByTagName("head")[0].appendChild(script);
|
||||
}
|
||||
|
||||
//console.log(xhr.dd);
|
||||
//document.getElementById(unit_id).innerHTML = text[0];
|
||||
//记录加载状态
|
||||
units_cache.set(unit_src,text[0]);
|
||||
units_dom_init.set(matche,unit_src);
|
||||
|
||||
//深度遍历加载
|
||||
var matches2 = matche.querySelectorAll("div[alp-unit]");
|
||||
//遍历
|
||||
matches2.forEach(matche => load_unit(matche,reinit));
|
||||
}
|
||||
};
|
||||
xhr.open('GET', unit_src, true);
|
||||
xhr.send();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//动态加载扫描指定的dom节点
|
||||
function scan_alp_units(dom){
|
||||
|
||||
//首先加载自己
|
||||
if (dom.getAttribute("alp-unit")!="")
|
||||
load_unit(dom,true);
|
||||
|
||||
/**动态扫描加载dom元素内的alpine的单元*/
|
||||
var matches = dom.querySelectorAll("div[alp-unit]");
|
||||
//遍历
|
||||
matches.forEach(matche => load_unit(matche,true));
|
||||
|
||||
}
|
||||
|
||||
|
||||
//装载units
|
||||
function load_all_alp_units() {
|
||||
|
||||
console.log("装载所有Alpine Unit");
|
||||
/**动态扫描加载文档中的所有可见的alpine的单元 */
|
||||
var matches = document.querySelectorAll("div[alp-unit]");
|
||||
//遍历
|
||||
matches.forEach(matche => load_unit(matche,false));
|
||||
|
||||
|
||||
};
|
||||
|
||||
window.onload = function() {
|
||||
console.log("页面和所有资源已加载完成!");
|
||||
// 在这里调用您的函数
|
||||
load_all_alp_units();
|
||||
};
|
||||
Reference in New Issue
Block a user