Javascript 我可以简化这个只向DOM添加脚本的脚本吗?
我将此作为起点,但意识到这取决于div是否存在 想知道我是否可以使用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
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;
您甚至不需要存在
(或者在某些特殊情况下甚至不需要
)——您可以在任何地方插入