uniapp H5 怎样在当前页面插入html元素

有时需要在单个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);
        }

 

posted @ 2021-09-06 16:08  fogwu  阅读(3529)  评论(0编辑  收藏  举报