javascript BEST PRACTICE - managing scripts / code reuse

白昼怎懂夜的黑 提交于 2019-12-04 05:08:19

The answer to this is simple - you create a library, or a framework that contains all of the utility function you have, then you load that library on all your pages. Because of browser caching, the only time the client will have to retrieve that file is on the initial load, so even if the file is fairly large, the client will only need to load it once.

This means that some sites, such as Stack Overflow, uses only a single master JavaScript file that contains most of the code needed for all of the pages on the site to function. Even though only a few of the functions may be needed on every single page, browser caching means that this method will be more efficient.

The other way to prevent this from happening is the create a small server-side file that will combine the multiple JavaScript on the server dynamically, and serve them when the client requests for them, for example:

<script src="/resource/js?load=file1,file2,file3" type="text/javascript></script>

However, this method is not recommended because it defeats browser caching. Therefore, the best practice is usually to maintain a large master JavaScript file that contains all of the code needed for the site to function, which is cached on the initial page load.

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