通过动态加载javascript来提高网站性能? [英] improving website performance by dynamically loading javascript?

查看:56
本文介绍了通过动态加载javascript来提高网站性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这是通常做的还是可能的(我是新手)
假设你有一个沉重的javascripted网站。基本上是一个web应用页面。如果页面的一部分是邮箱...并且用户不一定立即使用它,该怎么办?您是否可以在页面加载后下载邮箱所需的javascript,甚至可能需要使用邮箱?我从另一个问题看到了这个:

I was wondering if this is something normally done or possible (I am a novice) suppose you have kind of a heavy javascripted site. A web app page basically. What if part of the page is a mailbox... and the user doesn't necessarily use it right away. Could you possibly download the javascript that the mailbox requires after the page has loaded or maybe even as they need to use the mailbox? I saw this from another question:

$.getScript("my_lovely_script.js", function(){

alert("Script loaded and executed.");


推荐答案

是的,你可以稍后加载非必要的脚本,以避免在显示初始页面之前处理它们。

Yes, you can load non-essential scripts "later" to avoid processing them before displaying the initial page.

有几种方法:


  1. 您可以将脚本标记标记为延迟或异步(请参阅 MDN以获取详细信息)因此浏览器将异步加载它并且不会阻止页面显示以加载或运行脚本。

  2. 您只能根据需要动态加载它。

  3. < body> 的末尾加载脚本< / body> 标记,以便页面可以在加载之前显示。

  1. You can mark the script tag as defer or async (see MDN for details) so the browser will load it asynchronously and not hold up page display for the loading or running of the script.
  2. You can load it dynamically only as needed.
  3. Load scripts at the end of the <body> right before the </body> tag so the page can display before they are loaded.



<在你走上这条道路之前,我强烈建议你这样做您可以测量页面的加载资源并找出时间的真正位置。在衡量实际发生的时间之前过早优化很少是改善事物的最有效方法。 Chrome调试器可以向您显示有关资源加载时间的大量数据。

Before you proceed down this path, I would highly suggest that you measure the loading resources of your page and find out where the time is really going. Premature optimization before you've measured where the time is actually going is rarely the most effective way to improve things. The Chrome debugger can show you a lot of data about resource load times.

另外,请记住,优化有效缓存的设计可以非常有效,因为您的脚本是加载到您网站的第一页,它们将被缓存用于所有未来的页面,并将非常快速地从浏览器磁盘或内存缓存加载。

Also, remember that a design that optimizes for effective caching can be highly effective since one your scripts are loaded for the first page on your site, they will be cached for all future pages and will load very, very quickly from the browser disk or memory cache.

这篇关于通过动态加载javascript来提高网站性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆