js 跨浏览器实现动态脚本和动态样式

2017-11-8 22:36:40 3,839 views

动态脚本

动态脚本:指的是在页面加载时不存在,但在将来的某一时刻通过修改dom动态添加的脚本

function loadScriptString (code) {
      var script=document.createElement("script");
      script.type="text/javascript";
      try{
        script.appendChild(document.createTextNode(code));
      }
      catch(ex){
        script.text=code;
      }
      document.body.appendChild(script);
    }
    loadScriptString("function say(){alert('hi')} say()");

动态脚本的2种创建方式

一:通过src特性包含外部文件

二:通过script元素本身包含代码

 

动态样式

动态样式:是指在页面刚加载时不存在的样式;动态样式是在页面加载时不存在的样式;动态样式是在页面加载完成后动态添加到页面中的

function loadStyleString(css) {
  var style = document.createElement("style");
  try {
    style.appendChild(document.createTextNode(css));
  } catch(ex) {
    style.styleSheet.cssText = css; //ie
  }
  var head = document.getElementsByTagName("head")[0];
  head.appendChild(style);
}
loadStyleString("body{background-color:red}");

动态样式的2种创建方式

一:通过link元素包含来自外部的文件

二:style元素用于指定嵌入的样式

0

分享到微信朋友圈

打开微信,点击底部的“发现”,
使用“扫一扫”即可将网页分享至朋友圈。