title: How to load google custom search onclick
body: <p>This is maybe a stupid question, but I'm a newbie with javascript...</p>
  
  <p>I have a static website that uses google custom search (V2). The script provided by Google loads asynchronously and that is good, but there are just a few searches a day, so I'm looking for a solution to load custom search "stuff" only if a user clicks in the search form, to have a faster pageload.</p>
  
  <p>I'm using two separate divs, one for the searchbox (hidden on a div to make my custom style) and one for search results (pop-up layout).</p>
  
  <pre><code>&lt;div class="hide-search"&gt;
      &lt;div class="gcse-searchbox-only"&gt;&lt;/div&gt; 
  &lt;/div&gt;
  &lt;form id="GOOGLE ID"&gt;
      &lt;input value="GOOGLE ID" name="cx" type="hidden" /&gt;
      &lt;input value="FORID:11" name="cof" type="hidden"/&gt;
      &lt;div class="column-twelve"&gt;
          &lt;input id="q" name="q" type="text" /&gt;
      &lt;/div&gt;
      &lt;div class="column-twelve"&gt;
          &lt;button type="submit" class="button mini"&gt;Search&lt;/button&gt;
      &lt;/div&gt;  
  &lt;/form&gt;
  </code></pre>
  
  <p>And later in the page</p>
  
  <pre><code>&lt;div class="gcse-searchresults-only"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>Before closing the body tag, I've added the following code provided by Google</p>
  
  <pre><code>&lt;script&gt;
  (function() {
  var cx = 'GOOGLE ID';
  var gcse = document.createElement('script');
  gcse.type = 'text/javascript';
  gcse.async = true;
  gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
      '//www.google.com/cse/cse.js?cx=' + cx;
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(gcse, s);
  })();&lt;/script&gt;
  </code></pre>
  
  <p>The website also uses jquery.</p>
  
  <p>Is there a way to load the script only if (and when) a user clicks on the search field? I wish to provide this search service to my users, but only if necessary and without harming pageload speed.</p>
  
  <p>Thanks in advance.  </p>
  
  <p><strong>UPDATE</strong>: </p>
  
  <p>Problem solved using jquery and php. The Google custom search script that I'm using reloads the page adding some GET variables.</p>
  
  <p>This is a ugly solution, but I moved the google script to an external .js file and added this code into the page:</p>
  
  <pre><code>&lt;?php
  if(isset($_GET['cx']))
  echo "
  &lt;script&gt;
  $.getScript( '../template/js/g-search.js'); 
  &lt;/script&gt;
  ";
  else echo"
  &lt;script&gt;
  $('#q').click(function(){
  $.getScript( '../template/js/g-search.js');
  })
  &lt;/script&gt;
  ";
  ?&gt;
  </code></pre>
  
  <p>In this way, if the user visits the page for the first time the script will load only if he clicks on the form input, speeding up pageload. If the page reloads after search button clicked, the script is loaded automatically and all is working well.</p>
  
  <p>Bad solution, but at least a solution!</p>