I’ve seen plugins that download third-party libraries and load them as local files from /vendor and others that require the library via a CDN.
Is one approach better than the other in terms of bandwidth/speed?
I’ve seen plugins that download third-party libraries and load them as local files from /vendor and others that require the library via a CDN.
Is one approach better than the other in terms of bandwidth/speed?
There’s a little bit of a grey area in between the two. You can set up Discourse to serve assets, including theme/plugin JS via a CDN. So, even if your plugin loads the external library in /vendor, it will be loaded from the CDN you configure Discourse to use. However, this is a private CDN.
That said, I don’t think that’s what you’re referring to. You’re referring to services like https://cdnjs.com and https://www.jsdelivr.com, and that’s a slightly different topic - a public CDN.
Services like cdnjs have a wide network of servers that are dedicated to that kind of thing.
So,
They can be faster, and they do help reduce the load on your server.
But… that speed benefit is also available if you use /vendor on a site that has configured Discourse to use a private CDN.
Also, regarding bandwidth, most external JS libraries are < 20Kb. So, while you do get some savings… it’s not really a major point unless your site gets hundreds of thousands of views daily.
One of the benefits of using something like cdnjs is that they serve the same file and have caching headers.
What does that mean? Well, let’s use jQuery, for example.
A lot of sites use jQuery, and a lot of them use cdnjs to deliver jQuery. When cdnjs delivers the jQuery file to the user, it includes caching headers - default to 1 year.
This means that if a user visits site A - which uses cdnjs for jQuery - and then visits site B, which also uses the same file with the same version, their browser won’t have to download jQuery again, since it’s cached - so that leads to faster page loading.
The point above is the biggest advantage to using something like cdnjs for your external libraries.
However, very few libraries are as common as jQuery, so it really depends on how common the library is.
When you load files from cdnjs, you’ll also need to make sure you add them to the CSP settings
So, I guess the answer here is… it depends.
Are you loading the library as is?
Is is common?
Is it on the larger side?
If so, maybe use a cdn. If not, keep it simple and just add it in /vendor
Small update here, Chrome, Safari and Firefox doesn’t work this way anymore. There is no more shared cache between sites:
有人能分享一个插件链接吗,该插件使用通过 /vendor 文件夹或 CDN 添加第三方库的方法?
我找不到任何相关文档,并且在将第三方库包含到我的插件、正确注册它、符合确切的文件夹结构以及在控制器文件中正确编写导入语句时遇到了麻烦。
提前感谢您的帮助!
discourse-math 可能是一个不错的参考——它在 /public 目录下有许多“已打包”的脚本。或者一个更简单的例子可以是 discourse-client-performance。