在HTML / PHP模板或单独的js文件中调用jQuery脚本的最佳方法是什么?

在HTML / PHP模板或单独的js文件中调用jQuery脚本的最佳方法是什么?

问题描述:

* is telling me this is a subjective question, but I think it's a matter of fact!

I have a number of scripts that I'm using on different parts of my site. In terms of making fewer http requests, I know it's better to combine all of these scripts into one .js file. However, isn't a waste of time for a page to call a .js full of 10 or 15 different functions when it's only using one?

The other method I am using is to use PHP conditional statements...

<?php if( is_page() ) { > 
     $(document).ready(function(){
          ...
     });
<?php } ?>

What's the best method or comination of these methods?

*告诉我这是一个主观问题,但我认为这是事实! p> \ n

我在网站的不同部分使用了许多脚本。 在减少http请求方面,我知道将所有这些脚本组合成一个.js文件会更好。 但是,如果一个页面仅使用一个函数来调用充满10或15个不同函数的.js并不浪费时间吗? p>

我正在使用的另一种方法是使用 PHP条件语句... p>

 &lt;?php if(is_page()){&gt;  
 $(document).ready(function(){
 ... 
}); 
&lt;?php}?&gt; 
  code>  pre> 
 
 

什么是 最好的方法还是这些方法的组合? p> div>

I would say, provided you expect users to require the vast majority of these resources as they browse your site, taking the hit all at once isn't much of an issue.

You need to make sure that your homepage loads quickly enough though, maybe consider a cut down script file for the homepage, and a fully bloated version for the other pages. Or separate out the truly required on every page features into a file that is included on the homepage, and the other features into an -extra file. Then include both files on pages which require them. The browser will already have cached the basic file from the homepage.

Seeing as the script file is cached by the browser and needs to be loaded only once, it is usually the smartest thing to in fact combine all JS code into one file.

It may be different if you have huge libraries upward of 100 kilobytes that get used only by certain users (e.g. users that log in). In such cases, it makes sense to make distinctions. Otherwise, I'd say go with one big file.