导读
- 日期:2022-1-18
分析网页时,经常遇到一些库未加载的情况,比如想使用axios库,该网站本身未加载,这时候就需要通过js加载。
通过CDN网站获取js的url
这里以axios
为例。
- https://www.bootcdn.cn/
- https://www.bootcdn.cn/axios
- https://cdn.jsdelivr.net/npm/axios@0.25.0/dist/axios.min.js
- https://www.jsdelivr.com/
- https://www.jsdelivr.com/?query=axios
- https://cdn.jsdelivr.net/npm/axios@0.25.0/dist/axios.min.js
url、script.src
function loadJS( url, callback ){
var script = document.createElement('script')
var fn = callback || function(){};
script.type = 'text/javascript';
//IE
if(script.readyState){
script.onreadystatechange = function(){
if( script.readyState == 'loaded' || script.readyState == 'complete' ){
script.onreadystatechange = null;
fn();
}
};
}else{
//其他浏览器
script.onload = function(){
fn();
};
}
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
// 测试代码
console.log(typeof axios)
loadJS('https://cdn.bootcdn.net/ajax/libs/axios/0.24.0/axios.js', ()=>console.log(typeof axios))
XHR加载、script.text
function loadJS( url, callback ){
var fn = callback || function(){};
var xhr = new XMLHttpRequest;
xhr.open('get',url,true);
xhr.onreadystatechange = function(){
if( xhr.readyState == 4 ){
if( xhr.status >=200 && xhr.status < 300 || xhr.status == 304 ){
var script = document.createElement('script');
script.type = 'text/javascript';
script.text = xhr.responseText;
//IE
if(script.readyState){
script.onreadystatechange = function(){
if( script.readyState == 'loaded' || script.readyState == 'complete' ){
script.onreadystatechange = null;
fn();
}
};
}else{
//其他浏览器
// axios的onload不会触发???
script.onload = function(){
fn();
};
script.onerror = function(e){
console.log('script.onerror', e)
};
}
document.body.appendChild(script);
}
}
};
xhr.send(null);
}
// 测试代码
console.log(typeof axios)
loadJS('https://cdn.bootcdn.net/ajax/libs/axios/0.24.0/axios.js', ()=>console.log(typeof axios))
参考资料
- js怎么动态加载js文件 https://www.cnblogs.com/telwanggs/p/11045773.html
- https://blog.csdn.net/Tmraz/article/details/114821997
- qq群:夜猫逐梦技术交流裙/953949723