简体   繁体   English

延迟 javascript 的加载,直到 jQuery 已正确加载

[英]Delay the loading of javascript until jQuery has been properly loaded

I'm trying to write a bookmarklet which involves dynamically adding two script tags, one for jQuery and the other for a js script written in jQuery.我正在尝试编写一个涉及动态添加两个脚本标签的书签,一个用于 jQuery,另一个用于用 jQuery 编写的 js 脚本。 The problem I'm having is that even though I add the jQuery script first, js script isn't able to be read because the browser says that jQuery is undefined.我遇到的问题是,即使我首先添加了 jQuery 脚本,js 脚本也无法读取,因为浏览器说 jQuery 未定义。 I know that the error is that jQuery is still being loaded as the browser adds my js script and as a result, the browser doesn't recognize the jQuery in the js script when it is executing the js script.我知道错误是 jQuery 仍在加载,因为浏览器添加了我的 js 脚本,因此,浏览器在执行 js 脚本时无法识别 js 脚本中的 jQuery。 Is there anyway to delay the adding of the js script tag until after jQuery is completely loaded?是否有延迟添加 js 脚本标签,直到 jQuery 完全加载之后?

Thanks!谢谢!

How do your script look like?你的脚本看起来如何?

You should encapsulate everything you do in the script in a function, which you then call from the document.您应该将您在脚本中所做的一切封装在 function 中,然后您可以从文档中调用它。

For instance put everything in the function myJqueryFunction() then call it with:例如将所有内容放入 function myJqueryFunction()然后调用它:

$(document).ready(function(){
    myJqueryFunction();
});

That makes your code only to execute once jQuery have fully loaded.这使得您的代码仅在 jQuery 完全加载后执行。

Alternatively, you should be able to execute your script using Ajax, but keep in mind that your script have to be served from the same domain as the document, otherwise it will not have access to the DOM.或者,您应该能够使用 Ajax 执行您的脚本,但请记住,您的脚本必须从与文档相同的域提供,否则将无法访问 DOM。

$(document).ready(function(){
    $.ajax("url to your script", {dataType:"script"});
});

The first thing that most Javascript programmers end up doing is adding some code to their >program, similar to this:大多数 Javascript 程序员最终做的第一件事就是在他们的 >program 中添加一些代码,类似于:

window.onload = function(){ alert("welcome"); }

Inside of which is the code that you want to run right when the page is loaded.其中是您要在页面加载时立即运行的代码。 Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads).然而,问题是,Javascript 代码在所有图像下载完成(包括横幅广告)后才会运行。 The reason for using window.onload in the first place is that the HTML 'document' isn't finished loading yet, when you first try to run your code.首先使用 window.onload 的原因是,当您第一次尝试运行代码时,HTML“文档”尚未完成加载。

Hopefully this information helps, -pulled from JQuery tutorial !希望这些信息有所帮助,从JQuery 教程中提取!

You can use a script loader like LABjs : http://labjs.com/ .您可以使用 LABjs 之类的脚本加载器: LABjs ://labjs.com/ It supports deferring other scripts using wait .它支持使用wait延迟其他脚本。

$LAB
.script("jquery.js")
.wait()
.script("script.js");

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

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