Home > Web Front-end > JS Tutorial > JavaScript method to dynamically load scripts and styles_javascript skills

JavaScript method to dynamically load scripts and styles_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 16:04:32
Original
1152 people have browsed it

One dynamic script

As the demand for the website increases, the demand for scripts also gradually increases; we have to introduce too many JS scripts and reduce the performance of the entire site;
So the concept of dynamic scripts emerged, loading the corresponding scripts at the right time;

1. Dynamically introduce js files

  var flag = true;
  if(flag){  
    loadScript('browserdetect.js');          // 调用函数,引入路径;
  }
  function loadScript(url){
    var script = document.createElement('script');   // 创建script标签;
    script.type = 'text/javascript';          // 设置type属性;
    script.src = url;                 // 引入url;
    document.getElementsByTagName('head')[0].appendChild(script);  // 将script引入<head>中;
  }
Copy after login

2. Dynamically execute js code

  var script = document.createElement('script');
  script.type = 'text/javascript';
  var text = document.createTextNode("alert('Lee')");  // 设置script标签内容;IE会报错;
  script.appendChild(text);
  document.getElementsByTagName('head')[0].appendChild(script);

  // PS:IE浏览器认为script是特殊元素,不能再访问子节点;
  // 为了兼容,可以使用text属性来代替;
  function loadScriptString(code){
    var script = document.createElement("script");
    script.type = "text/javascript";
    try{
    // IE浏览器认为script是特殊元素,不能再访问子节点;报错;
      script.appendChild(document.createTextNode(code));  // W3C方式;
    }catch(ex){
      script.text = code;                    // IE方式;
    }
    document.body.appendChild(script);
  }
  // 调用;
  loadScriptString("function sayHi(){alert('hi')}");
Copy after login

2 Dynamic Style

In order to dynamically load style sheets, such as switching website skins;
There are two ways to load styles, one is the tag, the other is the