最近采用VUE做客服相关的系统,由于依赖第三方js,因此需要根据不同环境引入js。
比如在外网引入a.js,在内网引入b.js,该场景可根据不同需求而调整。
中间尝试了一些方法,都不行,当然,加载该js需要在VUE初始化之前,不然会导致系统加载不了相关方法。
思考在三,决定从VUE的index.html文件着手。通过vue-cli生成的项目的index.html文件如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>vuehr</title>
<script src="a.js"></script>
</head>
<body style="margin:0px;padding: 0px;">
<noscript>
<strong>We're sorry but vuehr doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
改造后的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>vuehr</title>
<!-- <script src="a.js"></script> -->
</head>
<script type="text/javascript">
var env = window.location.href;
var url = "";
if (env.indexOf("aaa") != -1) {
url = "\<script src=\'a.js\'>\<\/script\>";
} else {
url = "\<script src=\'b.js\'>\<\/script\>";
}
document.write(url);
</script>
<body style="margin:0px;padding: 0px;">
<noscript>
<strong>We're sorry but vuehr doesn't work properly without JavaScript enabled. Please enable it to
continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
当然,script中是否添加参数defer或async,可根据项目实际情况决定是否添加。具体defer或async可参考https://segmentfault.com/q/1010000000640869。
如果,你觉得本文对你有帮助,请点赞、收藏或评论,谢谢。
一些相关参考文档:
https://segmentfault.com/q/1010000012182845