improving website performance by dynamically loading javascript?

限于喜欢 提交于 2019-12-02 09:39:03

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

There are several approaches:

  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.

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.

Yes, this is possible and is done.

You can add script tags to the document when ever you want. You can also use a utility like LabJs to help you do it.

http://labjs.com/

Yes you can delay loading of your scripts, however what you should probably do is go to something like https://developers.google.com/speed/pagespeed/ and see what's taking so long and optimize on that. It's very possible that you'll see more overall performance by employing techniques such as loading from multiple domains simultaneously, and using tools like https://github.com/mishoo/UglifyJS2 to combine, compress, and minify your js code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!