简体   繁体   English

如何在页面加载后加载Google的自定义搜索引擎(CSE)JS API?

[英]How to load Google's Custom-search-engine(CSE) JS APIs after page loads?

I am using Google Custom Search Engine with their new auto-completion feature. 我正在使用Google自定义搜索引擎及其新的自动完成功能。 I want this whole javascript to be loaded AFTER the page itself is loaded. 我希望在页面本身加载后加载整个javascript。 The original Google code is this: 原始的Google代码是这样的:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load('search', '1');
  google.setOnLoadCallback(function() {
    google.search.CustomSearchControl.attachAutoCompletion(
      'some-long-unique-id',
      document.getElementById('q'),
      'cse-search-box');
  });
</script>
<script type="text/javascript" src="http://www.google.com/cse/brand?form=cse-search-box&lang=cs"></script>

I have transformed this code using tutorial about JS dynamic loading to this code: 我已经使用关于JS动态加载的教程将此代码转换为此代码:

(function() {
  var goog = document.createElement('script'); goog.type = 'text/javascript';
  goog.src = 'http://www.google.com/jsapi';
  var cse = document.createElement('script'); cse.type = 'text/javascript';
  cse.src = 'http://www.google.com/cse/brand?form=cse-search-box&lang=cs';
  goog.onload = function() {
    google.load('search', '1');
    google.setOnLoadCallback(function() {
      google.search.CustomSearchControl.attachAutoCompletion(
        'some-long-unique-id',
        document.getElementById('q'),
        'cse-search-box');
    });
  };
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(cse, s);
  s.parentNode.insertBefore(goog, s);
})();

Well, even though I think my solution should work(the same way has Google changed their Analytics on-demand asynchronous code), it doesn't. 好吧,即使我认为我的解决方案应该可行(谷歌改变他们的分析按需异步代码的方式相同),但事实并非如此。 The page loads fine and as soon as CSE loads, the page goes blank. 页面加载正常,一旦CSE加载,页面就会变为空白。 Something clears the DOM, I suppose its some kind of "Google thing" ? 什么东西清除DOM,我想它是某种“谷歌的东西”? Can someone bring some light on this problem and possibly a working solution ? 有人能否解决这个问题,可能还有一个有效的解决方案?

Thanks 谢谢

OK, so by checking Google Loader Developer's Guide and by lots of trying-and-testing I've figured how to change my code so it works as I expected in my question: 好的,所以通过检查谷歌加载器开发人员指南和大量的尝试和测试,我已经想到如何更改我的代码,以便它像我在我的问题中预期的那样工作:

(function() {
  var goog = document.createElement('script'); goog.type = 'text/javascript';
  goog.src = 'http://www.google.com/jsapi';
  goog.onload = function() {
    google.load('search', '1', {"callback": function() {}});
    google.setOnLoadCallback(function() {
      google.search.CustomSearchControl.attachAutoCompletion(
        'some-long-unique-id',
        document.getElementById('q'),
        'cse-search-box');
    });
  };
  var cse = document.createElement('script'); cse.type = 'text/javascript';
  cse.src = 'http://www.google.com/cse/brand?form=cse-search-box&lang=cs';
  var s = document.getElementsByTagName('script')[0]; 
  s.parentNode.insertBefore(cse, s);
  s.parentNode.insertBefore(goog, s);    
})()

The main thing is this line: 主要是这一行:

google.load('search', '1', {"callback": function() {}});

If you don't specify callback (at least empty function as I do), then the whole page goes blank, when Google's CSE loads. 如果你没有指定回调(至少是空函数),那么当谷歌的CSE加载时,整个页面都会变成空白。 I have no idea why, but it works fine now with this dummy callback function. 我不知道为什么,但现在使用这个虚拟回调函数工作正常。

Hope it helps someone with the same problem. 希望它可以帮助有同样问题的人。

我想你可以使用一些js加载器(例如yepnope ),它允许你按需加载js并添加一个回调。

I don't fully-understand what you're trying to achieve. 我不完全明白你想要实现的目标。 You've asked for someone to suggest how to 'correct' your code, but you haven't given any context, or what you actually want the end-result to be. 您已经要求某人建议如何“更正”您的代码,但您没有给出任何上下文,或者您真正想要的最终结果。

Also, the updates you've provided with the function()s you've written- it's not clear how these are being called. 此外,您已经使用函数()提供的更新 - 您不清楚如何调用这些更新。 In the when the document readyState is complete? 在文件readyState完成时?

Firstly, I'd suggest using jQuery to wrap up the JavaScript stuff. 首先,我建议使用jQuery来包装JavaScript的东西。 Yes, Google provide onload events and other helpers for their API, but jQuery will apply to any Javscript, there's no point in using two Javascript frameworks where you don't have to. 是的,谷歌为他们的API提供onload事件和其他助手,但jQuery将适用于任何Javscript,使用两个你不需要的Javascript框架是没有意义的。

The jQuery might be like this: jQuery可能是这样的:

<script type="text/javascript" language="javascript" src="/js/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript" language="javascript">
    // Use the jQuery document load functionality.
    $(document).ready(function ()
    {
        // Load the Google API asynchronously.  The callback 'GoogleApiLoaded' will be called when the script is fully-loaded.
        $.getScript("http://www.google.com/jsapi?key=yourkey", GoogleApiLoaded);    
        // Load other scripts, do other init code here (non-Google-dependent).
    });

    function GoogleApiLoaded()
    {
        // Google-related init here.
        // Load the custom search API.
        // (Could make the callback an in-line function).
        $.getScript("http://www.google.com/cse/brand?form=cse-search-box&lang=cs", CustomSearchApiLoaded);
    }

    function CustomSearchApiLoaded()
    {
        google.load('search', '1', LoadCustomSearchControl);
    }

    function LoadCustomSearchControl()
    {
        google.search.CustomSearchControl.attachAutoCompletion('some-long-unique-id', document.getElementById('q'), 'cse-search-box');
    }
</script>

It might be helpful to break the code apart into different functions, in order to track-down more easily where the problem is. 将代码拆分为不同的功能可能会有所帮助,以便更容易地跟踪问题所在。 That you have to put in an optional callback on the 'google.load()' function is strange- it may be a bug in the Google code, there are some floating around. 你必须在'google.load()'函数中添加一个可选的回调是很奇怪的 - 它可能是谷歌代码中的一个错误,有一些浮动。

I've used google.load('search', '1', LoadCustomSearchControl) , rather than the google.setOnLoadCallback , because as far as I can see they should do the same thing, and using a callback on load() is neater, in my view. 我使用了google.load('search', '1', LoadCustomSearchControl) ,而不是google.setOnLoadCallback ,因为据我所知他们应该做同样的事情,并且在load()上使用回调更整洁, 在我看来。

I'd strongly advise you use jQuery (or any JavaScript framework), as it makes life a lot easier. 我强烈建议你使用jQuery(或任何JavaScript框架),因为它使生活变得更容易。

I'd be interested to see whether what I've suggested works, and if not where it goes wrong. 我有兴趣看看我建议的是否有效,如果没有出错。 (Make sure to add-in your own JSAPI key). (确保添加自己的JSAPI密钥)。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM