创建 Javascript API,如 Facebook 和 Twitter [英] Creating Javascript API like Facebook and Twitter

查看:22
本文介绍了创建 Javascript API,如 Facebook 和 Twitter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑为我的应用程序创建 javascript API 方法,类似于 Facebook 或 Twitter Javascript SDK 的工作方式.有人可以就可以帮助我类似地开发 Javascript 方法的资源提出建议.我打算做以下事情:

I am looking at creating javascript API methods for my application similar to how the Facebook or the Twitter Javascript SDK works. Could someone please advice on resources that can help me develop Javascript methods similarly. I intend to do the following:

  • 用户应该能够异步加载 Javascript.
  • 在加载 Javascript 后,调用一个方法在特定元素上加载 iframe.

感谢人们是否可以帮助我实现这一目标?

Appreciate if people could help me on how to achieve this?

推荐答案

做这样的事情很简单.

异步加载库很容易,与facebook无关,它是javascript的东西,例如使用facebooks的例子:

Loading the library asynchronously is easy, and has nothing to do with facebook, it's a javascript thing, for example using facebooks' example:

(function(d){
    var js, 
        id = "LIB_ID", 
        ref = d.getElementsByTagName('script')[0];

    if (d.getElementById(id)) {
        return;
    }

    js = d.createElement("script");
    js.id = id;
    js.async = true;
    js.src = "URL_OF_LIB";
    ref.parentNode.insertBefore(js, ref);
}(document));

这将异步加载您的 js.

That will load your js asynchronously.

为了能够通知"库已加载,您可以使用 facebook 正在使用的方法在窗口上定义回调,因此您的库的用户将执行以下操作:

In order to be able to "notify" that the library is loaded you can use the method facebook is using which is to define a callback on the window, so the user of your lib will do something like:

window.libLoaded = function() {
        // Do what ever when the library is loaded
}

在您的 lib 代码中,最后只需调用该回调:

And in your lib code, at the end just call that callback:

window.libLoaded();

动态创建 iframe 也非常简单:

Creating an iframe dynamically is very easy as well:

function loadFrame(url, domEl) {
        var frame = document.createElement("iframe");
        frame.src = url;
        domEl.appendChild(frame);
}

但是,您将无法在 iframe 文档和主文档之间进行通信,因为(我假设)它们不会共享同一个域,并且由于同源策略,浏览器会阻止这种情况.

However, you won't be able to communicate between the iframe document and the main document since (I assume) they won't share the same domain, and the browser will prevent that due to the same origin policy.

这篇关于创建 Javascript API,如 Facebook 和 Twitter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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