当前位置:网站首页>如何动态添加script依赖的脚本
如何动态添加script依赖的脚本
2022-08-04 03:47:00 【行致】
如何动态添加script依赖的脚本
使用的背景
在我们平常开发中,会在HTML文件中会放置一些所依赖的脚本,但在有些情况下,区分不同的环境下,而加载不同的脚本,或者相同的脚本而不同的版本,这就需要动态添加了
具体放置方法
可以动态的创建script元素,然后脚本链接赋值给src,但要注意一点,在加载完这个脚本之后才能进行下一步,否则放置的脚本可能没有生效或者是已经执行完而所依赖的脚本还在加载中。这是很重要的一点。
我所使用的框架是vit+react+ts进行开发的,因此我动态添加的script元素是放置在app.tsx中。具体代码如下:例 动态加载不同版本的微信sdk版本
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter } from 'react-router-dom';
import {
getEnv } from '@/utils';//区分微信环境和企业微信环境
import App from './app';
// 根据环境插入不同js-sdk,按目前文档企业微信插入1.2,微信插入1.6
const script = document.createElement('script');
// script.crossOrigin = 'anonymous';
if (getEnv() === 'qywx') {
script.src = 'https://res.wx.qq.com/open/js/jweixin-1.2.0.js';
script.onerror = () => {
window.$log('qy-wx-sdk:loadError');
};
} else {
script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
script.onerror = () => {
window.$log('wx-sdk:loadError');
};
}
script.onload = rcInit;//加载完script后,渲染页面dom
document.head.appendChild(script);
function rcInit() {
ReactDOM.render(
<BrowserRouter basename="/admin-app">
<App />
</BrowserRouter>,
document.getElementById('root')
);
}
边栏推荐
- 【Ryerson情感说话/歌唱视听数据集(RAVDESS) 】
- 嵌入式数据库开发编程MySQL(全)
- Eight guiding principles to help businesses achieve digital transformation success
- 【医保科普】维护医保基金安全,我们可以这样做
- Oracle与Postgresql在PLSQL内事务回滚的重大差异
- TOML configuration file format, YAML's top contender
- Postgresql source code (66) insert on conflict grammar introduction and kernel execution process analysis
- Introduction to the memory model of the JVM
- 复现20字符短域名绕过
- Postgresql源码(66)insert on conflict语法介绍与内核执行流程解析
猜你喜欢
sql注入一般流程(附例题)

4-way two-way HDMI integrated business high-definition video optical transceiver 8-way HDMI high-definition video optical transceiver

数组相关 内容 解析

说说数据治理中常见的20个问题
![[Ryerson emotional speaking/singing audiovisual dataset (RAVDESS)]](/img/f7/78eea9f14ca97b5e78592c7c2be313.png)
[Ryerson emotional speaking/singing audiovisual dataset (RAVDESS)]

软件测试如何系统规划学习呢?
SQL injection in #, - +, - % 20, % 23 is what mean?

三分建设,七分管理!产品、系统、组织三管齐下节能降耗

MySQL查询优化与调优

Eight guiding principles to help businesses achieve digital transformation success
随机推荐
【机器学习】21天挑战赛学习笔记(一)
SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropri
Reproduce 20-character short domain name bypass
本周四晚19:00知识赋能第4期直播丨OpenHarmony智能家居项目之设备控制实现
2022支付宝C2C现金红包PHP源码DEMO/兼容苹果/安卓浏览器和扫码形式
基本表单验证流程
SQL query String field less than 10 how to check
什么是数字孪生智慧城市应用场景
Polygon zkEVM网络节点
类如何只能静态分配和只能动态分配
嵌入式数据库开发编程MySQL(全)
The keytool command
base address: environment variable
STM8S105K4T6------Serial port sending and receiving
MySQL查询优化与调优
if,case,for,while
出现504怎么办?由于服务器更新导致的博客报504错误[详细记录]
移动支付线上线下支付场景
目标检测-中篇
Sfdp 超级表单开发平台 V6.0.5 正式发布