动态加载js在的在项目中的应用:
由于产品与项目的分离,产品提供的视图或函数不能够满足各个项目特殊需求时,则需要提供相应的js注入入口提供给项目做二次开发。如产品提供页面有一系列内容呈现,但项目不想用,则可以以注入的方式重写产品页面。或者产品预览dom提供项目作为扩展。以下方式简单方式模拟这一实现。
1、创建demo 文件夹;
2、demo文件夹下创建index.html页面。代码如下↓
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<style type="text/css">
</style>
</head>
<body>
<div id="olddom">我是原页面文档</div>
<div id="custom_div"></div>
</body>
<script type="text/javascript">
var hs = {};
var rootPath = "";
//模拟common.js
$(function() {
locationMatch = function(match) {
if (typeof match != "string")
return false;
if (match == '')
return true;
var matchs = match.split(',');
var currUrl = window.location.href;
var index = currUrl.indexOf('/', 8);
if (index >= 0)
currUrl = currUrl.substr(index).toLowerCase();
else
currUrl = '/';
for (var i = 0; i < matchs.length; i++) {
if (matchs[i] != '') {
var s = matchs[i].toLowerCase();
if (s.substr(s.length - 1, 1) == "*") {
s = s.substr(0, s.length - 1);
var reg = new RegExp("^" + rootPath.toLowerCase() + s);
if (reg.test(currUrl))
return true;
} else {
if (currUrl == rootPath.toLowerCase() + s)
return true;
}
} else {
if (currUrl.substr(currUrl.length - 1, 1) != "/")
currUrl += "/";
if (currUrl == rootPath.toLowerCase())
return true;
}
}
return false;
};
/**
* 动态载入js文件
* @param {Object} match 匹配路径,多个用逗号分隔,相对于根路径,为空将匹配所有路径
* @param {Object} jsUrl 加载的JS文件,相对于根路径
* @param {Object} callback 加载成功后的回调
*/
hs.loadStript = function(match, jsUrl, callback) {
if (typeof jsUrl == 'string' && jsUrl != '' && locationMatch(match)) {
$.getScript(rootPath + jsUrl, callback);
}
};
}());
//index页自己的js
$(function() {
hs.customJs = (function() {
var init = function() {
hs.loadStript("/demo/index.*", "indexEx.js", function() {
hs2.common.init();
});
};
return {
init: init
};
}());
hs.customJs.init();
});
</script>
</html>
3、demo文件夹下创建 indexEx.js。该js文件模拟项目注入用。实现代码如下↓
var hs2={};
hs2.common=(function(){
var init=function(){
$("#olddom").hide();
$("#custom_div").html('<span style="color:red;font-size:18px;">test.js 注入成功!</span>')
};
return{
init:init
}
}());
4、浏览器运行index.html 运行如下↓
至此,所有操作就搞定了。至于应用场景中需要封装,模块化、js方法注入、元素替换等……就各自发挥了。有用别忘了点个赞!