0

Issue - Error

I get this error,

  • Error: CSE.js:130 Uncaught ReferenceError: google is not defined

Issue - Description

  • However, if I use the chrome console in web tools, if google.search.... is used, it works.

  • not sure why google isn't loading in the context of my code, please help.

Code

    // Generate CSE Script
    let scr  = document.createElement('script'),
    head = document.head || document.getElementsByTagName('head')[0];
    scr.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//www.google.com/cse/cse.js?cx=' + cse_cx;
    scr.async = false; // optionally
    head.insertBefore(scr, head.firstChild);

    // Get Results Element
    let element = google.search.cse.element.getElement('searchresults-only0');

after code executes, etc.

  • doing this will work

enter image description here

4
  • is the google library imported? Commented Apr 23, 2020 at 17:26
  • 2
    is it loaded before you invoke it? Commented Apr 23, 2020 at 17:28
  • @MKant yes, it loaded via js then i try to execute my code, perhaps should i do some kind of onload or ducment ready? Commented Apr 23, 2020 at 17:31
  • 1
    Run your last statement inside a window.onload wrapper or move it to the end of the body tag so the script has time to load. Commented Apr 23, 2020 at 17:31

2 Answers 2

2

You might want to use the Search Element initialization callback in this case. Check out https://developers.google.com/custom-search/docs/element#init-callback

Sign up to request clarification or add additional context in comments.

Comments

0

So adding a "Delay" works,

I wrapped my code with a setTimeout(function(){ /*CODE HERE*/ }, 1000); after dynamically injecting the script.

2 Comments

While this workaround might "solve" the problem for you it is not a good idea to do it that way. You should check if the library provides a way to figure out if it is loaded.
the delay is not a perfect solution to be honest though the code might work. What you should be doing is figure out if you have a handler in the library which gives you a way to execute the code afterwards the library is done loading

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.