JavaScript

超轻量级php框架startmvc

JS实现动态添加外部js、css到head标签的方法

更新时间:2020-08-30 12:54:01 作者:startmvc
本文实例讲述了JS实现动态添加外部js、css到head标签的方法。分享给大家供大家参考,具体

本文实例讲述了JS实现动态添加外部js、css到head标签的方法。分享给大家供大家参考,具体如下:


function appendJQCDN() {
 var head = document.head || document.getElementsByTagName('head')[0];
 var script = document.createElement('script');
 var style = document.createElement('style');
 script.setAttribute("src", "https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js");
 style.innerHTML = '';
 head.appendChild(script);
 head.appendChild(style);
}

动态添加 js


function loadScript(url, callback) {
 var script = document.createElement("script");
 script.type = "text/javascript";
 if (typeof (callback) != "undefined") {
 if (script.readyState) {
 script.onreadystatechange = function () {
 if (script.readyState == "loaded" || script.readyState == "complete") {
 script.onreadystatechange = null;
 callback();
 }
 };
 } else {
 script.onload = function () {
 callback();
 };
 }
 };
 script.src = url;
 document.body.appendChild(script);
}


loadScript("https://cdn.bootcss.com/jquery/3.2.1/jquery.js", function() { 
 //加载,并执行回调函数
 alert('动态引入jquery成功')
});

JS 动态添加 外部 js css head标签