开发者

Can I load JavaScript code after the rest of page loads?

开发者 https://www.devze.com 2023-01-05 23:24 出处:网络
I have a section of a webpage that loads a JavaScript file from an external source and then kicks off an Ajax query.

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 sayin开发者_StackOverflow社区g "waiting for example.com" 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?


It'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.com/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.com/ssoroka/sigma

Sigma.async_script_load('http://example.com/underscore/underscore-min.js', '_', function() {
  _([1,2,3,2,3,1]).uniq();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消