jQuery 页面完全加载后加载jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19026345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
load jquery after the page is fully loaded
提问by Ashkan Mobayen Khiabani
I'm looking for a way to load jquery after the page is fully loaded.
well there are lots of questions and answers about it in here, but all describe how to run a script that needs jquery after either page or jquery fully loaded.
What I'm looking for is to load the page and then call jquery and after the jquery is loaded call the functions. something like:
我正在寻找一种在页面完全加载后加载 jquery 的方法。
好吧,这里有很多关于它的问题和答案,但都描述了如何在页面或 jquery 完全加载后运行需要 jquery 的脚本。
我正在寻找的是加载页面,然后调用 jquery,加载 jquery 后调用函数。就像是:
document.onload=function(){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.7.2.min.js');
//Here I need an event to know that jquery is
//loaded to run stuff that needs jquery
}
采纳答案by Ashkan Mobayen Khiabani
I have asked this question more than 6 years ago, and any answers I got had some flaws. Later I myself worked out a solution that I have been using for years since then. Now that I came across my own question again and I saw that it has many views, I'd like to share it because I think it may help others.
我在 6 多年前问过这个问题,我得到的任何答案都有一些缺陷。后来我自己制定了一个解决方案,从那时起我一直在使用。现在我又遇到了我自己的问题,看到它有很多观点,我想分享它,因为我认为它可以帮助别人。
This problem mainly occurs on Master-Detail type of pages (can be old .master and .aspx pages) or (layout and views in asp.net) or any similar situation maybe on other web development languages, however always there is a master-detail pattern involved.
这个问题主要发生在 Master-Detail 类型的页面(可以是旧的 .master 和 .aspx 页面)或(asp.net 中的布局和视图)或任何类似的情况可能在其他 Web 开发语言上,但总是有一个 master-涉及的细节模式。
For the solution, I just add an array at the beginning of my page:
对于解决方案,我只是在我的页面开头添加了一个数组:
<script>var after = [];</script>
any function that requires jQuery or any other script that would run after this section, instead of running it, I just push it to this array:
任何需要 jQuery 或将在本节之后运行的任何其他脚本的函数,而不是运行它,我只是将它推送到这个数组:
after.push(function(){
// code that requires scripts that will load later,
//might be for example a jQuery selector or ...
});
and then at the very end of the page, right before closing the body tag (of course scripts are loaded by now) I run all the functions inside the (here named) after
array:
然后在页面的最后,就在关闭 body 标记之前(当然脚本现在已经加载)我运行(此处命名的)after
数组中的所有函数:
<script>for(var i=0;i<after.length;i++)after[i]();</script>
</body>
I find this way very easy, simple and flawless.
我发现这种方式非常容易、简单和完美。
回答by Mr.Turtle
Try this:
尝试这个:
$(document).ready(function() {
// When the document is ready
// Do something
});
回答by umar_
You can also use:
您还可以使用:
$(window).bind("load", function() {
// Your code here.
});
回答by Drachenfels
For your problem, the solution might be to attach CDN hosted by google with certain library:
对于您的问题,解决方案可能是将 google 托管的 CDN 附加到某些库中:
https://developers.google.com/speed/libraries/devguide
https://developers.google.com/speed/libraries/devguide
Also, you can add this at the bottom of page (just before </body>
):
此外,您可以在页面底部(就在 之前</body>
)添加此内容:
<script type="text/javascript">
(function() {
var script = document.createElement('script')
script.setAttribute("type", "text/javascript")
script.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js")
document.getElementsByTagName("head")[0].appendChild(script)
})();
</script>
However, this is risky in my opinion. You have an asynchronous call for jquery, thus your jquery has to wait until it loads (ie. $(document).ready
won't work in this case). So my answer would be: use a CDN like google suggests; put your javascript on the bottom just before </body>
; and, ignore flags from profilers.
然而,在我看来,这是有风险的。你有一个对 jquery 的异步调用,因此你的 jquery 必须等到它加载(即$(document).ready
在这种情况下不起作用)。所以我的答案是:使用像谷歌建议的 CDN;将您的 javascript 放在底部之前</body>
;并且,忽略来自分析器的标志。
回答by Andy Zee
It is advised to load your scripts at the bottom of your <body>
block to speed up the page load, like this:
建议在<body>
块底部加载脚本以加快页面加载,如下所示:
<body>
<!-- your content -->
<!-- your scripts -->
<script src=".."></script>
</body>
</html>
回答by Nishu Tayal
回答by Irvin Dominin
You can try using your function and using a timeout waiting until the jQuery object is loaded
您可以尝试使用您的函数并使用超时等待 jQuery 对象加载
Code:
代码:
document.onload=function(){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.7.2.min.js');
document.getElementsByTagName("head")[0].appendChild(fileref);
waitForjQuery();
}
function waitForjQuery() {
if (typeof jQuery != 'undefined') {
// do some stuff
} else {
window.setTimeout(function () { waitForjQuery(); }, 100);
}
}
回答by nirazul
My guess is that you load jQuery in the <head>
section of your page. While this is not harmful, it slows down page load. Try using this pattern to speed up initial loading time of the DOM-Tree:
我的猜测是您在<head>
页面的部分加载了 jQuery 。虽然这无害,但会减慢页面加载速度。尝试使用此模式来加快 DOM-Tree 的初始加载时间:
<!doctype html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<!-- PAGE CONTENT -->
<!-- JS -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(function() {
$('body').append('<p>I can happily use jQuery</p>');
});
</script>
</body>
</html>
Just add your scripts at the end of your <body>
tag.
只需在<body>
标签末尾添加脚本即可。
There are some scripts that need to be in the head due to practical reasons, the most prominent library being Modernizr
由于实际原因,有一些脚本需要在头脑中,最突出的库是Modernizr
回答by Gurminder Singh
回答by tikider
if you can load jQuery from your own server, then you can append this to your jQuery file:
如果您可以从您自己的服务器加载 jQuery,那么您可以将其附加到您的 jQuery 文件中:
jQuery(document).trigger('jquery.loaded');
jQuery(document).trigger('jquery.loaded');
then you can bind to that triggered event.
然后您可以绑定到该触发事件。
回答by Josiah
If you're trying to avoid loading jquery until your content has been loaded, the best way is to simply put the reference to it in the bottom of your page, like many other answers have said.
如果您试图避免在加载内容之前加载 jquery,最好的方法是简单地将对其的引用放在页面底部,就像许多其他答案所说的那样。
General tips on Jquery usage:
Jquery 使用的一般提示:
Use a CDN.This way, your site can use the cached version a user likely has on their computer. The
//
at the beginning allows it to be called (and use the same resource) whether it's http or https. Example:<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
使用 CDN。这样,您的站点就可以使用用户可能在其计算机上拥有的缓存版本。在
//
一开始允许它被称为(并使用相同的资源),无论是HTTP或HTTPS。例子:<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Using a CDN has a couple of big benefits: it makes it more likely that users have it cached from another site, so there will be no download (and no render-blocking). Further, CDNs use the closest, fastest connection available, meaning that if they do need to load it, it will probably be faster than connecting to your server. More info from Google.
使用 CDN 有两个很大的好处:它使用户更有可能从另一个站点缓存它,因此不会有下载(也不会阻塞渲染)。此外,CDN 使用最近、最快的可用连接,这意味着如果他们确实需要加载它,它可能会比连接到您的服务器更快。来自谷歌的更多信息。
Put scripts at the bottom.Move as much of your js to the bottom of the page as possible. I use php to include a file with all my JS resources below the footer.
If you're using a template system, you may need to have javascript spread throughout the html output. If you're using jquery in scripts that get called as the page renders, this will cause errors. To have your scripts wait until jquery is loaded, put them into
window.onload() = function () { //... your js that isn't called by user interaction ... }
将脚本放在底部。将尽可能多的 js 移动到页面底部。我使用 php 在页脚下方包含一个包含所有 JS 资源的文件。
如果您使用的是模板系统,您可能需要在整个 html 输出中使用 javascript。如果您在页面呈现时调用的脚本中使用 jquery,这将导致错误。为了让您的脚本等到jQuery是加载,把它们放到
window.onload() = function () { //... your js that isn't called by user interaction ... }
This will prevent errors but still run before user interaction and without timers.
这将防止错误,但仍会在用户交互之前运行且无需计时器。
Of course, if jquery is cached, it won't matter too much where you put it, except to page speed tools that will tell you you're blocking rendering.
当然,如果 jquery 被缓存了,你把它放在哪里并不重要,除非页面速度工具会告诉你正在阻止渲染。