Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我可以简化这个只向DOM添加脚本的脚本吗?_Javascript_Dom - Fatal编程技术网

Javascript 我可以简化这个只向DOM添加脚本的脚本吗?

Javascript 我可以简化这个只向DOM添加脚本的脚本吗?,javascript,dom,Javascript,Dom,我将此作为起点,但意识到这取决于div是否存在 想知道我是否可以使用appendChild将脚本直接附加到document.body // loads a script using the DOM and an optional argument to bust the cache function loadScript(path, bust) { console.log("Loading | " + path + " | " + bust) const ref = document.g

我将此作为起点,但意识到这取决于div是否存在

想知道我是否可以使用
appendChild
将脚本直接附加到document.body

// loads a script using the DOM and an optional argument to bust the cache
function loadScript(path, bust) {
  console.log("Loading | " + path + " | " + bust)
  const ref = document.getElementsByTagName( 'div' )[ 0 ];
  const script = document.createElement( 'script' );
  if(bust){
    path = path + '?cache_buster=' + bust;
  }
  script.src = path;
  ref.parentNode.insertBefore( script, ref );
}
每个答案

// loads a script using document.body and an optional argument to bust the cache
function loadScript(path, bust) {
  if(bust){
    path = path + '?cache_buster=' + bust;
  }
  document.body.appendChild(document.createElement('script')).src = path;
  console.log("Loading | " + path + " | ");
}
想知道我是否可以使用appendChild将脚本直接附加到
document.body

当然可以。只要脚本不依赖于它在DOM中的位置(例如,只要它不引用
document.currentScript
来查看附近的元素,
标记的位置是不相关的

document.body.appendChild(document.createElement('script')).src = path;
您甚至不需要存在
(或者在某些特殊情况下甚至不需要
)——您可以在任何地方插入