有時需要在單個vue頁面引用js,官方給出的辦法是在網站發行時通過自定義模板路徑中插入需要使用的元素。例如登陸頁面需要引入QQ的 jssdk。由於vue是單頁面程序,如果加在模板頁面,所有頁面都會引用這個jssdk。會影響頁面的加載速度。對於其它頁面這個jssdk也是多余的。
官方H5配置介紹: https://uniapp.dcloud.io/collocation/manifest?id=h5
解決方法:
vue 的mounted用於html加載完成后執行,可以在這個周期加入需要引入的js文件,為了給這個js一定的加載時間,可以再使用setTimeout 延遲加載后的操作
mounted() { let e=document.createElement('script'); e.src="//connect.qq.com/qc_jssdk.js"; e.setAttribute("data-appid", "100520993"); e.setAttribute("data-redirecturi", "100520993"); document.head.appendChild(e); setTimeout(()=> { if(QC.Login.check()) { QC.Login.getMe((openId, accessToken)=> { getParamsRequest("/user/user.ashx",{"act":"qqLogin","openId":openId},true).then(res => { location.href=res.data; console.log(res); }).catch(res => { showToast('連接超時'); that.isDisplay=false; }); }); } },500); }