为其他网站创建一个 javascript 小部件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2411501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a javascript widget for other sites
提问by TheWebGuy
I am looking to create a javascript "widget" that can be hosted on other sites. For example. I want to host the javascript code on my site:
我希望创建一个可以托管在其他网站上的 javascript“小部件”。例如。我想在我的网站上托管 javascript 代码:
http://scripts.mysite.com/mywidget.js
http://scripts.mysite.com/mywidget.js
(Think of it like Google Analytics).
(把它想象成谷歌分析)。
Basically I want to distribute data via this javascript. But what I am unsure of is:
基本上我想通过这个javascript分发数据。但我不确定的是:
- Are the rules different for development when creating a javascript for another site (cross site)
- Are there any websites that explain these differences?
- 为另一个站点(跨站点)创建 javascript 时,开发规则是否不同
- 是否有任何网站可以解释这些差异?
回答by PatrikAkerstrand
I would try to:
我会尝试:
Make it configurable
- Load external stylesheets?
- Where do I find resources I need? (images, stylesheets)
- What layout/size should I have?
By doing this you let the user decide if he wants your widget to automatically load the stylesheet, or if he wants to host it himself. If he does, he can also update the styles to better fit the page the widget resides on.
- Provide a wizardfor generating a snippet of code to include on the page
- Ensures that even moderately technical users can utilize your widget
- Make it light-weight
- Serve everything minified and compressed
- Serve with cache-headers, e-tags, last-modified and all other useful headers you can think of. This will both reduce the load on your servers as well as make your widget more responsive.
- Try to avoid dependencies on libraries, or check if they are loaded on the page where the widget is used before loading them
- Be wary of conflicts
- Prototype uses $, and so does jQuery. If your widget depends on Prototype, and the page it is hosted on uses jQuery without noConflict-mode, problems WILL arise
- Do not clobber the global namespace!
- If you don't want anyone to interact with your widget, put it in a self-executing function in a closure and don't create any global variables at all
- If you want users to be able to interact with your widget, say for adding event listeners and such, claim a single global variable, let's say ExampleComWidget as an object literal and put your methods there. User's could then interact like:
ExampleComWidget.addListener('update', callback);
Use clever markup
Be sure to use scoping on your classes and ids, to avoid conflicts as much as possible
I.e. if your company's name is example.com, you could use classes like:
com-ex-widget-newsItem- Validate your markup! You do not want to break a user's site
- Semantic markup is fine, but you might want to avoid
<h1>-tags, since they have especially high ranking in SEO. You could probably get by with using<h4>and less. This bullet might be a bit off. When in doubt, it's much better to use semantic markup than not.
- Fetch data from your site by inserting script elements
- This is a fool-proof way to ensure that you get around the same-origin restrictions.
- Attach an onload-listener to the script element to know when the data is ready, or use jsonp
使其可配置
- 加载外部样式表?
- 我在哪里可以找到我需要的资源?(图像,样式表)
- 我应该有什么布局/尺寸?
通过这样做,您可以让用户决定是希望您的小部件自动加载样式表,还是希望自己托管它。如果这样做,他还可以更新样式以更好地适应小部件所在的页面。
- 提供用于生成要包含在页面上的代码片段的
向导
- 确保即使技术中等的用户也可以使用您的小部件
- 让它重量轻
- 提供所有缩小和压缩的内容
- 使用缓存头、电子标签、上次修改和您能想到的所有其他有用的头。这将减少您服务器上的负载并使您的小部件更具响应性。
- 尽量避免依赖库,或者在加载之前检查它们是否加载到使用小部件的页面上
- 警惕冲突
- Prototype 使用 $,jQuery 也是如此。如果您的小部件依赖于 Prototype,并且它所在的页面使用没有noConflict-mode 的jQuery,则会出现问题
- 不要破坏全局命名空间!
- 如果您不希望任何人与您的小部件交互,请将其放在闭包中的自执行函数中,并且根本不要创建任何全局变量
- 如果您希望用户能够与您的小部件进行交互,例如添加事件侦听器等,声明一个全局变量,假设 ExampleComWidget 作为对象文字并将您的方法放在那里。然后用户可以进行如下交互:
ExampleComWidget.addListener('update', callback);
使用巧妙的标记
一定要对你的类和 id 使用范围,尽可能避免冲突
即,如果您公司的名称是 example.com,您可以使用如下类:
com-ex-widget-newsItem- 验证您的标记!您不想破坏用户的站点
- 语义标记很好,但您可能希望避免使用
<h1>-tags,因为它们在 SEO 中的排名特别高。您可能可以通过使用<h4>和减少来解决。这颗子弹可能有点不对劲。如有疑问,使用语义标记比不使用要好得多。
- 通过插入脚本元素从您的站点获取数据
- 这是确保您绕过同源限制的万无一失的方法。
- 将 onload-listener 附加到 script 元素以了解数据何时准备就绪,或使用jsonp
回答by Alex Jasmin
Your script should not interfere with the rest of the page.
您的脚本不应干扰页面的其余部分。
- Keep the number of globals to a minimum (one namespaceobject should be enough)
- Don't add properties to the built-in objects for no reason
- Don't expect to be the only script that listen for events such as window.onload
- If you're using for..in loops keep in mind that other scripts may have added stuff to Array.prototype
- Take style-sheets into consideration. The default style of HTML elements may have been changed.
- Don't update your script without reason as you risk breaking a lot of sites.
- 将全局变量的数量保持在最低限度(一个命名空间对象就足够了)
- 不要无缘无故地向内置对象添加属性
- 不要期望成为唯一监听 window.onload 等事件的脚本
- 如果您使用 for..in 循环,请记住其他脚本可能已向 Array.prototype 添加内容
- 考虑样式表。HTML 元素的默认样式可能已更改。
- 不要无故更新您的脚本,因为您可能会破坏许多站点。
回答by Leonid Titov
What PatrikAkerstrand said, is totally, 100% right.
PatrikAkerstrand 所说的完全 100% 正确。
What I want to add here, is a framework in vanilla JS that can save you a lot of time and effort to implement it, as everything is thought of, polished, and tested. All is left is to define your own widgets, and use them.
我想在这里添加的是一个 vanilla JS 框架,它可以为您节省大量的时间和精力来实现它,因为一切都经过思考、完善和测试。剩下的就是定义您自己的小部件并使用它们。
Here's an example of what it looks like.
这是它的外观示例。
小部件代码// inside a js file of a widget class
(function () {
var Module_Path = ["WidgetsLib", "a1", "Button"];
var curr = this;
Module_Path.forEach(function(i){if (curr[i] == null) {addChildToTree(curr, i, {})} curr = curr[i]});
specialize_with(curr, {
CSS_Literal: `
.{{WIDGET_CLASS_ID}}_Something {
color: hsl(0, 0%, 20%);
}
`,
HTML_Literal: `
<div onclick="{{WIDGET_INSTANCE}}.onclick(event)"
class="{{WIDGET_CLASS_ID}}_Something"
>
SOME SUPER COOL WIDGET
</div>
`,
new: typical_widget_new,
});
})();
一个 HTML:
<div id="w1" style="background-color: hsl(200, 50%, 50%);"></div>
<script src="WidgetsLib/a1/Button/js"></script>
用户 JavaScript 代码:
var b1 = WidgetsLib.a1.Button.new("w1", {
onclick: function(ev) {
ev.target.style.color = "#ffff00";
console.log("====== HERE");
}
});
Please download, and open the Widget_v2.md.html in a browser, it's https://github.com/latitov/JS_HTML_Widgets.
请下载并在浏览器中打开 Widget_v2.md.html,它是https://github.com/latitov/JS_HTML_Widgets。
What you'll get:
你会得到什么:
- very interesting article about this;
- snippets of code and examples;
- ready to use... framework in vanilla JS, to create widgets of your own;
- 关于这个的非常有趣的文章;
- 代码片段和示例;
- 准备好使用... vanilla JS 框架,创建您自己的小部件;
And enjoy creating re-usable widgets of your own, of arbitrary complexity, easily!
并享受轻松创建您自己的、任意复杂性的可重复使用的小部件!

