简体   繁体   English

在HTML页面中何处加载JavaScript脚本

[英]Where to load javascript scripts in html page

I am developing a jquery page and I think it is a little bit slow when you load it because I load all js files at the begining. 我正在开发一个jquery页面,我认为它在加载时会有点慢,因为一开始我会加载所有js文件。

Would it be faster if I load just which I need at the begining and in each section, loads which I need?. 如果我一开始只加载需要的内容,并且在每个部分中都加载需要的内容,会更快吗?

Now my webpage has all script calling in and after that, in all sections, home, page2, page3... 现在,我的网页上以及之后的所有部分(首页,第2页,第3页)都调用了所有脚本...

I structurated the webpage in one html file and I navigate to each section. 我将网页结构化为一个html文件,然后导航至每个部分。 Each section is like this: 每个部分都是这样的:

<div data-role="page" id="secion2" data-theme="e">
<!--<script type='text/javascript' src='javascript/createFbAlbums.js'></script> -->
**LOAD SCRIPTS HERE**
<div data-theme = "f" data-role="header" data-id="fixedNav" data-position="fixed">
    <h1>Page 2</h1>
    <a href="#home" data-icon="home" data-iconpos="notext"></a>

</div> <!-- /header -->
<div data-role="content">
     <ul data-role="listview" data-inset="true" class="managementEvents">   
        <li data-theme = "f"><a href="#expositivo">Page2</a></li>
        <li data-theme = "f"><a href="#page3">Modify Exposiciones</a></li>
    </ul>        
</div> <!-- /content -->

Loading them in sections like the commented in this piece of code. 将它们加载到本代码段中注释的部分中。 Is this equal to load at the begining or not? 这是否等于开始时的负载?

Or doing something like this inside javascript: 或在javascript中执行以下操作:

$(document).on("pageinit", '#section2', function(){
**LOAD HERE SCRIPTS**
Javascript code here doing everything in that page
});

I am a little bit lost because I don't know if this is ok or will break the page or will not speedup the loading. 我有点迷路,因为我不知道这是否可以,是否会破坏页面或无法加快加载速度。

The usual recommendation (for instance, in YUI's Best Practices for Speeding Up Your Web Site ) is that unless you have a good reason to do something else, put your scripts at the very end of the page, just before the closing </body> tag: 通常的建议(例如,在YUI的“加快网站速度的最佳做法”中 )是,除非您有充分的理由要做其他事情,否则请将脚本放在页面的最后,紧挨着</body>标签:

<p>Content</p>
<div>More content</div>
<script src="/some/script.js"></script>
</body>
</html>

Side note: This also makes it essentially unnecessary to use jQuery's ready feature. 旁注:这也使得从根本上不需要使用jQuery的ready功能。 If the script is at the very bottom of the page, all of the elements defined by the markup above it are available for scripting. 如果脚本位于页面的最底部,则该脚本上方标记所定义的所有元素都可用于脚本编写。

There's lots more useful advice in the page linked above. 上面链接的页面中还有很多有用的建议。 For example: To the extent possible, combine all of your scripts into a single file. 例如:尽可能将所有脚本组合到一个文件中。 (And make the file cachable, etc., etc.) (并使文件可缓存等)。

The downside : If you have content on your page that requires JavaScript to work correctly, the above means that the events related to that won't be hooked up right away. 缺点 :如果页面上有需要 JavaScript正常工作的内容,则上述内容意味着不会立即关联与此事件相关的事件。 There can be a brief window of time between the content being available to the user, and the event handlers being registered. 在内容可供用户使用和事件处理程序被注册之间可能存在短暂的时间间隔。 To deal with that, the concept of "progressive enhancement" comes into play: Make things work well without JavaScript, and then make them work better with JavaScript. 为了解决这个问题,“渐进增强”的概念发挥作用:让事情没有 JavaScript正常工作,然后让他们 JavaScript更好的作品。 Things that just can't work without JavaScript should be added by the JavaScript, or loaded initially-hidden and then shown by the JavaScript. 如果没有JavaScript,就无法正常工作的事物应由JavaScript添加,或先隐藏后再由JavaScript显示。

Whenever possible, JS files should be loaded at the bottom of the page. 尽可能将JS文件加载到页面底部。 Prior to the closing body tag. 在关闭身体标签之前。

http://developer.yahoo.com/performance/rules.html#js_bottom http://developer.yahoo.com/performance/rules.html#js_bottom

The reason is that JS files loading can block parallel downloads of other page assets. 原因是JS文件加载会阻止其他页面资产的并行下载。 So they can cause a bottleneck. 因此它们可能导致瓶颈。

In addition to that advice, since you're using jQuery, load jQuery from a CDN such as Google. 除了该建议外,由于您使用的是jQuery,请从CDN(例如Google)中加载jQuery。 There are a couple of benefits to doing that: 这样做有很多好处:

  • a popular CDN such as Google increases the odds that the end-user has already cached the JS library 诸如Google之类的流行CDN增加了最终用户已经缓存JS库的几率
  • it further reduces the parallel downloading bottleneck as it's another domain (the bottleneck is per-domain) 它进一步减少了并行下载瓶颈,因为它是另一个域(瓶颈是每个域)

The recommendation is to put JavaScripts at the bottom of the page. 建议将JavaScript放在页面底部。 This does not take into account dynamically loading your scripts, however, because there are differences in how browsers actually handle downloading external resources such as JS files between using tags and dynamically loading via JavaScript DOM manipulation. 但是,这没有考虑动态加载脚本的情况,因为在使用标记和通过JavaScript DOM操作动态加载之间,浏览器实际处理下载外部资源(例如JS文件)的方式有所不同。

Further Explanation 进一步说明

Browsers load HTML and any embedded resources synchronously as they parse the HTML. 浏览器在解析HTML时同步加载HTML和任何嵌入式资源。 This means that as your page loads, when you have scripts up front, the loading of the page stops, the browser makes a request to download, then parse and evaluate/execute the JavaScript file, and then continues to load the rest of the HTML. 这意味着在页面加载时,当您前面有脚本时,页面的加载将停止,浏览器将发出下载请求,然后解析和评估/执行JavaScript文件,然后继续加载其余HTML 。 It does this with each script. 它对每个脚本执行此操作。

Therefore, unless there are crucial elements that need to use some JS functions or variables during page load, and in some cases this is needed, it's better to load the JS at the bottom of the page because your page will render quicker. 因此,除非在页面加载期间需要使用某些JS函数或变量的关键元素(在某些情况下需要这样做),否则最好将JS加载到页面底部,因为您的页面会更快地呈现。 And in those crucial cases, only load enough JS to get the page load done as quick as possible. 在那些紧急情况下,仅加载足够的JS即可尽快完成页面加载。

As an interesting aside, loading JS files dynamically using JavaScript itself (ie, dynamically inject script objects via javascript after page load), those scripts will load asynchronously and further improve page load times. 有趣的是,使用JavaScript本身动态加载JS文件(即在页面加载后通过javascript动态注入脚本对象),这些脚本将异步加载并进一步缩短了页面加载时间。

So to answer your question , 因此,为了回答您的问题

If you use the jQuery.ready() method of loading JS, it conforms to a best practice since the scripts will load after the page has already been loaded by the browser. 如果使用加载JS的jQuery.ready()方法,则它符合最佳实践,因为脚本将在浏览器已加载页面之后加载。 This is in effect even better than placing tags at the bottom of the page. 实际上,这比在页面底部放置标签更好。

$(document).ready(function () {
    $.getScript( "yourScript.js" )
});

(Full example for jQuery getScript can be found here for more in-depth examples: http://api.jquery.com/jquery.getscript/ (有关jQuery getScript的完整示例,请参见此处,以获取更深入的示例: http ://api.jquery.com/jquery.getscript/

You should always put your scripts at the bottom of your page before closing </body> tag 关闭</body>标记之前,应始终将脚本放在页面底部

Refer here for more informations why you should do it. 请参阅此处以获取更多信息,为什么要这样做。

是的,正如每个人都提到的那样,将脚本放在</body>标记之前的页面底部不会有任何问题,而将脚本放在head标记中的某个时间可能会造成问题。

如果您使用$(document).ready(function(){然后添加您的代码,并使用})关闭它,则实际上不必将脚本放在HTML末尾,尽管这两种方法都具有相同的效果被认为是良好的编程习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM