在文档准备就绪之前,Javascript onload 事件和其他事件

Javascript onload event and other events before the document is ready

本文关键字:事件 onload 其他 Javascript 文档 准备就绪      更新时间:2023-09-26
if (typeof $ == "undefined"){
console.log("$ is undefined. Adding javascript element to the document");
jQs = document.createElement("script");
jQs.type = 'text/javascript';
jQs.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
var s = document.getElementsByTagName('script')[0]; 
s.parentNode.insertBefore(jQs, s);
// Run script once jQuery is loaded
    console.log(" startScript() Start");
    jQs.onload = startScript;
}

我得到了上面的脚本,它添加一个脚本标签,如果 $ 未定义,则指向 jquery。我尝试在文档开始之前插入标签并执行 startScript 函数。但我认为发生的是 body.onload 没有足够快地触发 startScript。这会阻止其执行。是否有一个事件会在jquery脚本标签/文档准备就绪后立即触发startScript?

我认为答案在于每当jquery标签准备就绪并且文档准备就绪时执行启动脚本。但我不知道如何达到效果。

请注意,将代码放在 $(document).ready() 中是一个不相关的解决方案,因为如果脚本中没有包含 jquery 文件,它将 $ 是未定义的

另请注意,我不想在 jquery 标签 onload 事件上执行 onload 函数,因为这可能意味着该函数被多次触发

  function init() {
    if (typeof $ == "undefined"){
    console.log("$ is undefined. Adding javascript element to the document");
    jQs = document.createElement("script");
    jQs.type = 'text/javascript';
    jQs.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(jQs, s);
    // Run script once jQuery is loaded
        console.log(" startScript() Start");
        jQs.onload = startScript;
    }
}
window.onload = init;