简体   繁体   English

我可以将Facebook Javascript SKD与动态脚本标签插入一起使用吗?

[英]Can I use the Facebook Javascript SKD with a dynamic script tag insert?

What am I trying to achieve. 我想达到什么目的。 To create a module that loads the Facebook Javascript SDK without having to paste that script tag into your HTML and manually enter your app details, yes this may seem like a waste of time but It seems to make more sense to me. 要创建一个加载Facebook Javascript SDK的模块,而不必将该脚本标签粘贴到您的HTML中并手动输入您的应用程序详细信息,是的,这似乎是在浪费时间,但对我来说似乎更有意义。 For example this module would take a config with your details and everything could be set via Javascript instead of the initialization code being in your HTML file and the rest of your logic being in your script files. 例如,此模块将使用您的详细信息进行配置,并且可以通过Javascript设置所有内容,而不是将初始化代码存储在HTML文件中,并将其余逻辑存储在脚本文件中。

My problem. 我的问题。 When I dynamically append the script and 当我动态附加脚本并

<div id="fb-root"></div>

I get an error 我得到一个错误

FB.init has already been called - this could indicate a problem

This seems strange to me because I only have once instance FB.init is called. 这对我来说似乎很奇怪,因为只有一次实例FB.init被调用。 Effectively my script is the same as if you would manually add the script tag into the html but I'm trying to achieve it dynamically. 实际上,我的脚本与您将脚本标记手动添加到html中的方式相同,但是我正在尝试动态实现它。

What I have tried. 我尝试过的。 I have read a lot of questions on here about using javascript to append and prepend elements, I have tried mostly all of those methods. 我在这里阅读了很多有关使用javascript追加和添加元素的问题,我尝试了所有这些方法。 I have read topics titled Dynamically Inserting Script with Javascript, these have been no help. 我已经阅读了标题为“使用Javascript动态插入脚本”的主题,这些都无济于事。

My method seems to be correct, but I still get these Facebook errors. 我的方法似乎是正确的,但是我仍然遇到这些Facebook错误。

My Markup. 我的标记。

<!DOCTYPE html>
    <head>
       <title></title>
    <head>
    <body>
        <script src="facebook.js"></script>
    </body>
</html>

My Javascript: 我的Javascript:

var Facebook = {};

Facebook = {
        config: {
        APP_ID: 'APP_ID',
        APP_URL: 'APP_URL',
        CHANNEL_URL: 'CHANNEL_URL'
    }

};

var fbEl = document.createElement('div');
fbEl.id = 'fb-root';
document.body.insertBefore(fbEl,document.body.children[0]);

var fbScript = document.createElement('script');
fbScript.type = 'text/javascript';
fbScript.innerHTML = '';
fbScript.innerHTML += 'window.fbAsyncInit = function() {\n';
fbScript.innerHTML +=   'FB.init({\n';
fbScript.innerHTML +=       'appId      : '+Facebook.APP_ID+',\n';
fbScript.innerHTML +=       'channelUrl : '+Facebook.CHANNEL_URL+',\n';
fbScript.innerHTML +=       'status     : false,\n';
fbScript.innerHTML +=       'cookie     : true,\n';
fbScript.innerHTML +=       'xfbml      : false \n';
fbScript.innerHTML +=   '});\n';

fbScript.innerHTML +=   '};\n';

fbScript.innerHTML +=   '(function(d, debug){\n';
fbScript.innerHTML +=   'var js, id = "facebook-jssdk", ref = d.getElementsByTagName("script")[0];\n';
fbScript.innerHTML +=   'if (d.getElementById(id)) {return;}\n';
fbScript.innerHTML +=   'js = d.createElement("script"); js.id = id; js.async = true;\n';
fbScript.innerHTML +=   'js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";\n';
fbScript.innerHTML +=   'ref.parentNode.insertBefore(js, ref);\n';
fbScript.innerHTML +=   '}(document, /*debug*/ false));';

document.body.insertBefore(fbScript,document.body.children[1]);

I do have the Facebook variables set correctly in my code this is for demonstrations sake. 我确实在我的代码中正确设置了Facebook变量,这只是为了演示。 I have read the Facebook Docs on this many times. 我已经多次阅读过Facebook文档。

Is there a way to dynamically add the block for tje FB JS SKD using ONLY Javascript? 有没有一种方法可以仅使用Javascript为tje FB JS SKD动态添加块?

I'm not sure what's actually going wrong, but you have one more level of indirection than you need and that's making the whole thing too complicated. 我不确定到底出了什么问题,但是您的间接访问级别超出了您的需要,这使整个事情变得太复杂了。 Why not something like: 为什么不这样:

var Facebook = {
   config:{ //etc
   }
};

window.fbAsyncInit = function() {
  FB.init(//etc
  )
};

(function(d, debug){
  var js, id = //etc - this injects the SDK script reference into the dom.
})(document, false);

The asynchronous JS code FB provide is a way to generate the FB SDK code only in javascript. FB提供的异步JS代码是仅在javascript中生成FB SDK代码的方法。 Right now it seems like you try to code PHP style into JS... 现在好像您尝试将PHP样式编码为JS ...

If you need to load modules asynchronously, you should use a module loader (RequireJS or YepNope, etc). 如果需要异步加载模块,则应使用模块加载器(RequireJS或YepNope等)。

The error message triggered may be because you added some parameter in the FB SDK URL (eg //connect.facebook.net/fr_CA/all.js#xfbml=1&appId=123456789" ). If so, just remove everything after the hash # . Also, make sure you're not loading the SDK twice. 引发该错误消息可能是因为您添加的FB SDK URL一些参数(例如//connect.facebook.net/fr_CA/all.js#xfbml=1&appId=123456789" )。如果是这样,刚散后删除一切#另外,请确保您没有两次加载SDK。

The method I was trying was causing a strange load order, the init code would load before the SDK was loaded causing strange errors. 我尝试的方法导致了奇怪的加载顺序,初始化代码将在加载SDK之前加载,从而导致奇怪的错误。

A revision of the logic solved this. 修改逻辑解决了这个问题。 Not much different but now it works perfectly. 差别不大,但现在可以正常使用。

Facebook = {};

Facebook = {
    config: {
        APP_ID: 'APP_ID',
        APP_URL: 'APP_URL',
        CHANNEL_URL: 'CHANNEL_URL'
    }

};
Facebook.init = function() {
    var fbEl = document.createElement('div');
    fbEl.id = 'fb-root';
    document.body.insertBefore(fbEl,document.body.children[0]);
    window.fbAsyncInit = function() {
    // init the FB JS SDK
        FB.init({
            appId      : 'APP_ID', // App ID from the App Dashboard
            channelUrl : 'CHANNEL_URL', // Channel File for x-domain communication
            status     : true, // check the login status upon init?
            cookie     : true, // set sessions cookies to allow your server to access the session?
            xfbml      : true  // parse XFBML tags on this page?
        });

        // Additional initialization code such as adding Event Listeners goes here

    };

    // Load the SDK's source Asynchronously
    // Note that the debug version is being actively developed and might 
    // contain some type checks that are overly strict. 
    // Please report such bugs using the bugs tool.
    (function(d, debug){
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
        ref.parentNode.insertBefore(js, ref);
    }(document, /*debug*/ false));
};

Facebook.init();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我是否应该始终使用动态脚本标记注入技术来包含javascript文件,类似于Facebook? - Should I always use dynamic script tag injection technique for including javascript files, similar to Facebook? 我可以使用 Element.insertAdjacentHTML() 插入标签脚本吗 - Can I use Element.insertAdjacentHTML() to insert tag script 我可以使用 Jquery 在动态表中插入结束标签和开始标签吗? - Can I use Jquery to insert a closing </tr> tag and an opening <tr> tag inside a dynamic table? 如果我添加动态脚本标记,则javascript无法正常工作 - javascript is not working if i add dynamic script tag 我该如何插入<script type='text/javascript' src=''> tag on a 3rd party webpage using rails? - How can I insert a <script type='text/javascript' src=''> tag on a 3rd party webpage using rails? 如何插入标签<br>使用 JavaScript 插入另一个标签? - How can I insert a tag <br> into another tag using JavaScript? Javascript:“取消”动态脚本标记? - Javascript: “Cancelling” a dynamic script tag? 是否可以插入和运行动态脚本标记? - Is it possible to insert and run a dynamic script tag? 如何使用带有JavaScript标签的php? - how can I use php with javascript tag? 如何在wordpress网站内使用PHP查找散列的bundle.js文件并将相应的文件名插入script标签? - How can I use PHP inside a wordpress site to find a hashed bundle.js file and insert the appropriate file name into the script tag?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM