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
Add a ment  | 

4 Answers 4

Reset to default 6

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./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