初面网初面网

动态生成内容

动态脚本

可以用创建元素之类的方法创建出script元素,然后将其添加到文档中。

const script = document.createElement('script');
script.src = 'foo.js';
document.body.appendChild(script);

甚至可以嵌入源代码

const script = document.createElement('script');
script.appendChild(document.createTextNode(`
  function sayHi(){alert('hi');}
`));
document.body.appendChild(script);

但上述代码在IE里可能不支持,因为IE不支持createTextNode方法。

所以为了兼容性,可以如下书写:

const script = document.createElement('script');
try {
  script.appendChild(document.createTextNode(`
    function sayHi(){alert('hi');}
  `));
} catch (e) {
  script.text = `
    function sayHi(){alert('hi');}
  `;
}
document.body.appendChild(script);

动态样式

两种样式,link和style。

const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'foo.css';
document.head.appendChild(link);
const style = document.createElement('style');
style.appendChild(document.createTextNode(`
  body(background-color:red)
`));
document.head.appendChild(style);

如果是IE浏览器,createTextNode方法可能不支持,需要使用styleSheet.cssText代替。

const style = document.createElement('style');
try {
  style.appendChild(document.createTextNode(`
    body(background-color:red)
  `));
} catch (e) {
  style.styleSheet.cssText = `
    body(background-color:red)
  `;
}
document.head.appendChild(style);

针对IE浏览器,需要注意,如果重用同一个style元素并设置该属性超过一次,浏览器可能会崩溃。将cssText设置为空字符串也可能导致浏览器崩溃。

更新于 2026/7/3