Our project contains many pages which has up to 20 tabs, each works with different scripts. All the script files are referenced in <head>
and loads on the first page load. Now we have performance issue because there are too many scripts on the page loads on opening it (about 2k lines of JavaScript per tab). The matter is in much cases user needs to work with 2-3 tabs and as a result more than 60% of code becomes not used. So we need any scripts lazy-loading solution to ease the pages. As HTML for every tab is loaded on demand we can put <script>
references in every tab that will provide a good working solution. But I'm prety sure including references not in <head>
is a bad style.
So I wonder, is there any another solution? How such problems are solved in big projects like us? Any advice will be helpfull.
Thanks in advance!
问问题
1704 次
1 回答
3
jQuery 为这个解决方案提供了一个很好的功能:
$.getScript("my_lovely_script.js", function(){
alert("Script loaded and executed.");
// here you can use anything you defined in the loaded script
});
默认情况下不缓存。我在 jQuery 网站上寻找了一个解决方案,它声明了这个缓存脚本包含的解决方案。
jQuery.cachedScript = function(url, options) {
// allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "script", //Note this
cache: true, //Enable caching
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
// Usage
$.cachedScript("URL HERE").done(function(script, textStatus) {
console.log( textStatus );
});
于 2012-05-03T08:14:07.167 回答