js 判断js,css是否引入,确保不重复引入

 
基本原理:
function loadjscssfile(filename, filetype){
if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement_x('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement_x("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
  document.getElementsByTagName_r("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

注意点:
默认挂在dom的第一个节点下,要保证不影响原有的页面的逻辑。
防止重复加载。
var filesadded="" //list of files already added

function checkloadjscssfile(filename, filetype){
if (filesadded.indexOf("["+filename+"]")==-1){
  loadjscssfile(filename, filetype)
  filesadded+="["+filename+"]" //List of files added in the form "[filename1],[filename2],etc"
}
else
  alert("file already added!")
}

checkloadjscssfile("myscript.js", "js") //success
checkloadjscssfile("myscript.js", "js") //redundant file, so file not added



我自己写的例子如下:
isexist这个变量要定义在需要引入的js里,用typeof去检测改变量是否存在?如果等于undefined,说明不存在,那就引入外部js,否则,就不引入!
    if(typeof(isexist) == 'undefined')
    {
        var fileref = document.createElement_x('script');
        fileref.setAttribute("type","text/javascript");
         fileref.setAttribute("src","<?php echo $html->url('/')?>js/valide.js");
        document.getElementsByTagName_r("head")[0].appendChild(fileref);
        
    }
原文地址:https://www.cnblogs.com/yangjing1314/p/7364768.html