开发者

Would on-the-fly .js inclusion (using jQuery) be considered bad or best practice?

I've built a core javascript "framework" for my web app, one of the methods on it is this:

include: function(url, success, cache) {
  $.ajax({ url: url, dataType: "script", success: success, cache: cache !== false })
}

It allows me to include jQuery plugins, and take action using them, on-the-fly. Like this:

Core.include('coolPlugin.js', fun开发者_StackOverflowction() { $obj.cool(); //... }, true);

This way I only need to include actual script tags for the initial import of jQuery from the Google CDN and my core library. All subsequently taken actions asynchronously include the script file as it's needed, and cached on the first connection.

If I wrap the Core.include in a $(document).ready(), it essentially turns it into a delayed import, for scenarios where that would be required.

I realize the primary drawback of this is the time it takes to load in the .js file. Are there other drawbacks I'm missing? Seems like this is a great practice, but don't want to overlook some looming catastrophe.

Would on-the-fly .js inclusion, as described above, be considered bad or best practice?


There are actually some valid arguments for this "deferred" loading technique. Mainly it speeds up the initial complete page load time, then scripts can be loaded after the fact "on demand" or after a short delay.

The answer to the "bad or best practice" part of your question is "it depends." If your site is very JS heavy, and can be effectively boken down into parts that can be loaded later, this is a technique that may work well for you. If your site has lower JS requirements, doing that might actually hurt your performance and certainly would add complexity to your code that it might not need.

I would consider this just one of your tools among many, and not necessarily "good" or "bad" on its own.

Also, check out these libraries, they provide some of this deferred functionality among other features, you might find them interesting:

  • http://requirejs.org/
  • http://headjs.com/


It would depend on environment to environment. I feel that too many scripts in the HEAD of doc­u­ment would even­tu­ally affect per­for­mance. But considering compressing and joining of scripts in one script-file reduce http loads, also helps.

So, thinking of split method, its better to load features-required-JS dynamically, as when invoked (there may be the cases when the certain feature will not be used even once). And let all essentials structural scripts to be loaded in head-section (preferably compressed and from CDN).

Happy Coding.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜