文档准备好之前的 Javascript onload 事件和其他事件

标签 javascript jquery html

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标签准备好并且文档一起准备好时执行startscript..但我不知道如何实现效果..

请注意,将代码放在 $(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;

关于文档准备好之前的 Javascript onload 事件和其他事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11100691/

相关文章:

javascript - 在 Javascript 中,是否有以下 : variable = variable = value; 的名称

javascript - Openlayers 3 坐标

jquery - 响应式图像悬停 - CSS/JQuery

javascript - 如何在 Rails 应用程序中安装 jQuery UI?

javascript - 使用 jquery mobile 和 cordova 无法刷新可折叠 ListView 的标题

javascript - jQuery 在 anchor 后插入按钮

javascript - 如何知道单击时选择了多少个类元素?

html - 具有白色背景的 PNG 在移动 Chrome 上呈现为透明

html - R:使用 rvest 抓取动态链接

jquery - 一个CSS3动画样式的源代码