admin管理员组文章数量:1323724
I have a section of a webpage that loads a JavaScript file from an external source and then kicks off an Ajax query.
When I load the page, I see the browser saying "waiting for example" a lot, so I think the dependency on this external JavaScript is slowing my initial page load.
Is there a way I can load this external JavaScript asynchronously so it doesn't slow the loading of the rest of my page at all?
I have a section of a webpage that loads a JavaScript file from an external source and then kicks off an Ajax query.
When I load the page, I see the browser saying "waiting for example." a lot, so I think the dependency on this external JavaScript is slowing my initial page load.
Is there a way I can load this external JavaScript asynchronously so it doesn't slow the loading of the rest of my page at all?
Share Improve this question edited Mar 21, 2014 at 5:45 Taryn East 27.8k9 gold badges88 silver badges110 bronze badges asked Jul 5, 2010 at 16:21 leoraleora 197k368 gold badges906 silver badges1.4k bronze badges 1-
1
defer
isn't widely supported. I deleted my answer. – Unicron Commented Jul 5, 2010 at 16:27
4 Answers
Reset to default 6It's good practice to put JS at the bottom, right above the closing body
tag. In addition, use load events window.onload
or $(document).ready()
to fire your JavaScript after the page has loaded.
As far as loading JavaScript files themself asynchronously or on demand, you could inject it from another JavaScript function or event. But really you are doing the same thing as placing it at the bottom.
Check out the YSlow Guidelines for front-end optimizations.
You could use jQuery's .getScript()
method, which is simply a wrapper for an AJAX call.
http://api.jquery./jquery.getscript/
This makes the request asynchronous, and gives you a callback that runs after the script has loaded.
You can see my answer here: Dynamic (2 levels) Javascript/CSS Loading
And grab the script from here (see the source). Use it at the bottom, and your scripts will not block other resources (and if you got more than one they will be downloaded in parallel cross-browser).
I wrote a library to asynchronously load javascript files with callbacks for when it loads:
https://github./ssoroka/sigma
Sigma.async_script_load('http://example./underscore/underscore-min.js', '_', function() {
_([1,2,3,2,3,1]).uniq();
});
本文标签: jqueryCan I load JavaScript code after the rest of page loadsStack Overflow
版权声明:本文标题:jquery - Can I load JavaScript code after the rest of page loads? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742124323a2421867.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论