每天get几个JavaScript小技巧(一)

加载 JS (外部)/ CSS(外部) / style
const loadRes = function (name, type, fn) { //加载 js || css || style
  let ref;
  if (type === 'js') { //外部JS
    ref = document.createElement('script')
    ref.setAttribute('type', 'text/javascript')
    ref.setAttribute('src', name)
  } else if (type === 'css') { //外部css
    ref = document.createElement('link')
    ref.setAttribute('rel','stylesheet')
    ref.setAttribute('type','text/css')
    ref.setAttribute('href',name)
  }else if(type === 'style') { //style
    ref = document.createElement('style')
    ref.innerHTML = name
  }
  if (typeof ref !== 'undefined') {
    document.getElementsByTagName('head')[0].appendChild(ref)
    ref.onload = function () { //加载执行完毕
      typeof fn === 'function' && fn()
    }
  }
}
获取URL参数
const getUrlParam = function(name) {
  let req = new RegExp('(^|&?)' + name + '=([^&]*)(&|$)', 'i')
  let r = window.location.href.substring(1).match(req)
  if(r !== null) {
    return decodeURI(r[2])
  }
  return undefined
}

你可能感兴趣的:(每天get几个JavaScript小技巧(一))