当前位置:网站首页>如何动态添加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')
);
}
边栏推荐
- new Date converts strings into date formats Compatible with IE, how ie8 converts strings into date formats through new Date, how to replace strings in js, and explain the replace() method in detail
- 用户与用户互发红包/支付宝C2C/B2C现金红包php源码示例/H5方式/兼容苹果/安卓
- MySQL查询优化与调优
- 汇编语言之栈
- Returns the maximum number of palindromes in a string
- Based on the statistical QDirStat Qt directory
- 外卖店优先级
- 深度学习——以CNN服装图像分类为例,探讨怎样评价神经网络模型
- sql注入一般流程(附例题)
- Brush esp8266-01 s firmware steps
猜你喜欢
随机推荐
MySQL query optimization and tuning
DIY电工维修如何拆卸和安装开关面板插座
Embedded database development programming MySQL (full)
Mockito unit testing
2千兆光+6千兆电导轨式网管型工业级以太网交换机支持X-Ring冗余环网一键环网交换机
4路双向HDMI综合业务高清视频光端机8路HDMI高清视频光端机
复现20字符短域名绕过
2022杭电多校联赛第五场 题解
【医保科普】维护医保基金安全,我们可以这样做
sql语句查询String类型字段小于10的怎么查
十一种概率分布
基于 SSE 实现服务端消息主动推送解决方案
FPGA parsing B code----serial 3
函数,递归以及dom简单操作
Asynchronous programming solution Generator generator function, iterator iterator, async/await, Promise
高效IO模型
MCU C language -> usage, and meaning
汇编语言之栈
打造一份优雅的简历
Architecture of the actual combat camp module three operations









