简体   繁体   English

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

[英]Javascript onload event and other events before the document is ready

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;

}

I have got the script above, which adds a script tag that points to jquery in the case if the $ is undefined. 我上面有脚本,如果$未定义,则添加一个脚本标记指向jquery。 I try to insert the tag before the document begins and execute the startScript function. 我尝试在文档开始之前插入标签并执行startScript函数。 But what I think happens is that the body.onload doesnt trigger the startScript fast enough.. and that prevents its execution. 但是我认为发生的是body.onload没有足够快地触发startScript ..并且阻止了它的执行。 Is there an event that would trigger teh startScript as soon as the jquery script tag / document is ready? jQuery脚本标记/文档准备好后,是否会立即触发startScript的事件?

I think the answer lies in executing the startscript whenever the jquery tag is ready and the document is ready together..but i dont know how to achieve the effect.. 我认为答案就在于每当jquery标签准备好并且文档一起准备好时执行startscript。.但是我不知道如何实现效果。

Note that putting the code in $(document).ready() is an irrelevant solution because it would $ is undefined if there is no jquery file included in the script 请注意,将代码放入$(document).ready()是不相关的解决方案,因为如果脚本中不包含jquery文件,则$是不确定的

note also that i dont want to execute the onload function on the jquery tag onload event,, cause it may mean that the function is being triggered several times 另请注意,我不想在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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM