This is maybe a stupid question, but I'm a newbie with javascript...
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.
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).
<div class="hide-search">
<div class="gcse-searchbox-only"></div>
</div>
<form id="GOOGLE ID">
<input value="GOOGLE ID" name="cx" type="hidden" />
<input value="FORID:11" name="cof" type="hidden"/>
<div class="column-twelve">
<input id="q" name="q" type="text" />
</div>
<div class="column-twelve">
<button type="submit" class="button mini">Search</button>
</div>
</form>
And later in the page
<div class="gcse-searchresults-only"></div>
Before closing the body tag, I've added the following code provided by Google
<script>
(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);
})();</script>
The website also uses jquery.
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.
Thanks in advance.
UPDATE:
Problem solved using jquery and php. The Google custom search script that I'm using reloads the page adding some GET variables.
This is a ugly solution, but I moved the google script to an external .js file and added this code into the page:
<?php
if(isset($_GET['cx']))
echo "
<script>
$.getScript( '../template/js/g-search.js');
</script>
";
else echo"
<script>
$('#q').click(function(){
$.getScript( '../template/js/g-search.js');
})
</script>
";
?>
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.
Bad solution, but at least a solution!