前端判断文件是否存在,并把获取到的js手动写入到head中

用两种方式,当在模块内开发,能够使用node的fs模块进行判断,不在模块内开发时,采用XMLHttpRequest和ActiveXObject进行判断

使用fs模块

const fs = require('fs')
fs.exists(filePath, (exists) => {      
	if (exists) {
		console.log("文件已存在");
	} else {
	  console.log("文件不存在");
   }
});

使用XMLHttpRequest和ActiveXObject

function isExistFile(filepath){
  if(filepath == null  || filepath === ""){
    return false
  }
  let xmlhttp = null
  if (window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest()
  }else{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
  }
  xmlhttp.open("GET",filepath,false)
  xmlhttp.send()
  if(xmlhttp.readyState === 4){
    if(xmlhttp.status === 200) return true //url存在
    else if(xmlhttp.status === 404) return false //url不存在
    else return false//其他状态
  }
}

js手动写入到head中

function addScript(url) {
  var script = document.createElement("script")
  script.setAttribute("type", "text/javascript")
  script.setAttribute("src", url)
  document.getElementsByTagName("head")[0].appendChild(script)
}

猜你喜欢

转载自blog.csdn.net/qq_42563079/article/details/124188685