为其他网站创建一个javascript小部件 [英] Creating a javascript widget for other sites

查看:100
本文介绍了为其他网站创建一个javascript小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望创建一个可以托管在其他网站上的javascript小部件。例如。我想在我的网站上托管javascript代码:

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:

http://scripts.mysite.com/mywidget.js

(想想它就像Google Analytics)。

(Think of it like Google Analytics).

基本上我想通过这个javascript分发数据。但我不确定的是:

Basically I want to distribute data via this javascript. But what I am unsure of is:


  • 在为另一个站点(跨站点)创建javascript时,开发规则是否不同

  • 是否有任何网站可以解释这些差异?

推荐答案

我会尝试:


  1. 使其可配置


  • 加载外部样式表?

  • 我在哪里可以找到所需的资源? (图片,样式表)

  • 我应该有什么布局/尺寸?

通过这样做您让用户决定他是否希望您的小部件自动加载样式表,或者他是否想要自己托管样式表。如果他这样做,他还可以更新样式以更好地适应窗口小部件所在的页面。

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.


  • 确保即使是技术熟练的用户也可以使用您的小部件


  • 服务所有缩小和压缩的物品

  • 提供缓存标题,电子标记,最后修改以及您可以想到的所有其他有用标题。这将减少服务器的负载,并使您的小部件更具响应性。

  • 尽量避免对库的依赖,或检查它们是否在使用小部件的页面上加载在加载之前


  • Prototype使用$,jQuery也是如此。如果您的小部件依赖于Prototype,并且它所托管的页面使用jQuery而没有 noConflict-mode ,问题将出现

  • 不要破坏全局命名空间!


    • 如果您不希望任何人与您的小部件进行交互,请将其放在闭包中的自执行函数中,并且不要创建任何全局变量

    • 如果您希望用户能够与您的窗口小部件进行交互,比如添加事件监听器等,请声明一个全局变量,让我们说ExampleComWidget作为对象文字并放置您的方法那里。然后用户可以像: ExampleComWidget.addListener('update',callback);

    • 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);

      使用聪明的标记


      • 请务必在您的班级和ID上使用范围,以尽可能避免冲突

      • Be sure to use scoping on your classes and ids, to avoid conflicts as much as possible

      即如果您公司的名称是example.com,您可以使用以下类: com-ex-widget-newsItem

      I.e. if your company's name is example.com, you could use classes like: com-ex-widget-newsItem


      • 这是一种确保您绕过同源限制的万无一失的方法。

      • 将onload-listener附加到script元素以了解数据何时就绪,或使用 jsonp

      • 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

      这篇关于为其他网站创建一个javascript小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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