I'm using Google Custom Search on my site with a two-page configuration: when the form is sent from page 1 to page 2, page 2 display SERP. This is my page 2:
<script>
(function() {
var cx = '00000000000';
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>
<gcse:searchresults-only queryParameterName="query"></gcse:searchresults-only>
</script>
Everything works fine as long as page two is a "classic" /page2.php?query=searchTerm.
Now I'd like to use mod_rewrite to switch to a friendlier /page2/searchTerm. The rule itself is done, but I cannot understand how to edit Google script to make it understand that now the parameter is mod_rewritten or how to use something like gcse.searchTerm='this is what I want to search for'.
API v1 is deprecated, so I need to stick with API v2.
Any help?
I don't think you need that. Why would you want search engine friendly search results URL? As far I understand SEO, you don't want your search results to appear as results on Google, Bing, etc.
And in my opinion www.example.com/search?q=test is much more "friendly" than www.example.com/page2/test because it is more obvious what it is. (Search results page.)
But, maybe I'm overlooking something, OK.
There are probably much better ways, but I think this should work also:
<script>
var searchFromURL = function() {
var element = google.search.cse.element.getElement('searchfromurlgname');
// you can echo query with PHP or get it from window.location
element.execute( window.location.pathname.replace('/page2/', '') );
};
var myCallback = function() {
if (document.readyState == 'complete') {
searchFromURL();
} else {
google.setOnLoadCallback(searchFromURL, true);
}
};
window.__gcse = {
callback: myCallback
};
(function() {
var cx = '013315504628135767172:d6shbtxu-uo';
// Insert your own Custom Search engine ID here
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>
<gcse:searchbox-only></gcse:searchbox-only>
<gcse:searchresults-only gname="searchfromurlgname"></gcse:searchresults-only>
<!-- switch CSE layout to "two page" -->
https://developers.google.com/custom-search/docs/element#tagparams
Related
I have a tool I am using that has embedded javascript to do tracking for it's hosted landing page.
I'd like to host the landing page on my own domain, and was hoping I could take the javascript and somehow manipulate it so that it would still track but from my page and I could not worry about the hosted page management.
Here is the code...any advice on if this is possible would be great!
<script type="text/javascript">
johnie = '225032';
ehe = '2846';
(function() {
function async_load(){
var s = document.createElement('script'); s.type = 'text/javascript';
s.src = ('https:' == document.location.protocol ? 'https://steve' : 'http://cdn') + ‘.steveo.com/pd.js';
var c = document.getElementsByTagName('script')[0]; c.parentNode.insertBefore(s, c);
}
if(window.attachEvent) { window.attachEvent('onload', async_load); }
else { window.addEventListener('load', async_load, false); }
})();
</script>
I have a Google Custom Search Element on my site configured to use the "Overlay Layout":
And I have a Google Analytics Profile conneced to this Google Custom Search account set under the relevant section like this:
I'm using the default Analytics code, and the Custom Search code Google vended.
Analytics "Site Search Tracking" is On at the "Reporting Views Settings" like this:
The problem:
No site search information is being collected by Analytics, even after several days.
This problem is only happening when I use the overlay Layout.
When I use a separate search results page, the query is being collected ok since the results page request is being recorded by Analytics.
With the overlay layout, the search results are being presented in an overlay Div and the query is going only through Google's Custom Search API.
The Question:
What can I do to make sure Analytics gets the keyword query?
Is there any callbak I'm missing?
Is there any thing else I'm missing?
The Solution:
After consulting with Google Support, here is the solution:
Set up the GCS account in admin console # https://www.google.com/cse
Set up in Analytics the Site Search settings as mentioned above
Use the Async Tracking Code of Analytics (Universal Analytics Code will not work as of May 2014). put it just before the closing tag. like this:
<head>
<!-- Your head tags, etc here -->
<script type="text/javascript">
var gaq;
var _gaq = gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-YY']);
_gaq.push(['_setDomainName', 'yourdoamin.com']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www')
+ '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
Put Use the GCS Tracking code you got from the admin console inside the secion
Use Custom call back to render the search box to handle custom attributes like this:
<body>
<script>
var customUIBehaviours = function(){
//your jQuery Post UI changes to the GCS box may come here
};
var renderSearchElement = function() {
google.search.cse.element.render({
div: 'gsd',
tag: 'search',
attributes:{
linkTarget:'_self',
gaQueryParameter: 'q',
gaCategoryParameter:'',
noResultsString:'No results.',
enableAutoComplete: true
}
});
};
var myCallback = function() {
if (document.readyState == 'complete') {
renderSearchElement();
customUIBehaviours();
} else {
google.setOnLoadCallback(function() {
renderSearchElement();
customUIBehaviours();
});
}
};
//this will make the GCS render by myCallback
window.__gcse = {
parsetags: 'explicit',
callback: myCallback
};
(function() {
var cx = 'YOUR GCS CODE HERE';
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>
<div id="gsd" class="gsce-searchBox"></div>
</body>
More information on the GCS V2 is available # https://developers.google.com/custom-search/docs/element#cse-element
I read somewhere that placing google analytics tracking code in seperate file is not recommended but I have no idea how to use it for my website (there are .php files and .tpl files and if I tried to put it almost everywhere and there was an error or it didn`t track the visitors).
Could anyone tell me which code I should put into separate .js file and in .tpl file so at least the basic functions would work? Thanks a lot!
This is the cleanest (using a anonymous auto-executing function):
(function() {
var _gaq = window._gaq = window._gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
Then reference in either your head or before end of body via:
<script type="text/javascript" src="YOUR_GA_CODE_LOCATION.js"></script>
you can write google analytics code in separate js file and include that js and call its function -
Suppose, following code is written in mygoogle.js
function loadMyGoogle()
window._gaq = window._gaq || [];
window._gaq.push([ '_setAccount',
'setaccounthere']);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl'
: 'http://www')
+ '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
}
then in your php files in header -
<head>
<include script="mygoogle.js">
</head>
In onload function of body tag -
function onload(){
loadMyGoogle();
}
I hope you know how you can set onload event in body tag
Do not put GA code in .js file instead include html page.
Steps:
1) Open notepad and paste GA code there.
2) Save it as HTML page
3) Include that html before end of head tag
I have been building script tag using javascript.when I use this script to load the three other scripts,the script is not loading in order.I want jquery.min.js to get loaded first. So I have used that as the first parameter. But it is not getting loaded at first. so I have been caught up with reference error. Can anyone tell me what mistake I have done in this code. My code is here
<script type="text/javascript">
(function (a, b, c) {
var g = document.createElement('script');
g.type = 'text/javascript';
g.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://') + a;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(g, s);
var g = document.createElement('script');
g.type = 'text/javascript';
g.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + b;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(g, s);
var g = document.createElement('script');
g.type = 'text/javascript';
g.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + c;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(g, s);
})('ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', '.example.com/js/script.js', '.example.com/js/form.js');
</script>
Use require.js for dynamic script loading.It will work.Also, try to use jquery.js above the website rather generate using script.
After my studing around this toppics, I updated for who visit to this question later.
For most of the browsers (IE9, Firefox, Chrome, Safari, ...) except Opera (12.16), dynamic script injection into DOM will load script asynchronously.
So this code:
function loadScript(src) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
}
loadScript('script1.js');
loadScript('script2.js');
loadScript('script3.js');
is almost equivalent to:
<script src="script1.js" async></script>
<script src="script2.js" async></script>
<script src="script3.js" async></script>
But if the async flag is set to false explicitly like:
function loadScript(src) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.async = false;
}
then the scripts will be loaded in order synchronously.
So the very short answer for this question is that g.async = false, but still I also recommend to use some framework and that is the best answer.
Try this: http://jsfiddle.net/DRCzN/
~~~~ original answer ~~~~~~
Dynamic script insertion (createElement('script') then insertBefore() or even insertAfter()) will load each script asynchronously.
So with your current script, the arrival of those script to the browser heavily depends on the network status.
If you want keep the dependency of these scripts, you can use some script loader such as $script, head.js or Require.js.
EDIT: I like Jonathan's solution, and here is a little improvement using $.getScript().
if script.js and form.js are independent of each other
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
(function(scripts) {
var protocol = ('https:' == document.location.protocol ? 'https://ssl.' : 'http://www.');
$.each(scripts, function(i, s) {
$.getScript(protocol + s);
});
})(['.example.com/js/script.js', '.example.com/js/form.js']);
</script>
if form.js depneds on script.js
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
(function(scripts) {
var protocol = ('https:' == document.location.protocol ? 'https://ssl.' : 'http://www.');
$.getScript(protocol + scripts[0], function() {
$.getScript(protocol + scripts[1]);
});
})(['.example.com/js/script.js', '.example.com/js/form.js']);
</script>
It's close, but use insertAfter, and remember to increase the index for each script.
var s = document.getElementsByTagName('script')[0];
g.parentNode.insertBefore(s, g.nextSibling);
...
var s = document.getElementsByTagName('script')[1];
g.parentNode.insertBefore(s, g.nextSibling);
...
var s = document.getElementsByTagName('script')[2];
g.parentNode.insertBefore(s, g.nextSibling);
Here's another example. This one uses an array of scripts to add, reverses them and then inserts after the current script tag.
EDIT: Can you get away with loading jQuery directly, as below. Using // a the start will make the resource load under the current protocol.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
(function (scripts) {
var protocol = ('https:' == document.location.protocol ? 'https://ssl.' : 'http://www.'),
thisScript = document.getElementsByTagName('script')[0];
function createScriptTag(element, index, array) {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = protocol + element;
thisScript.parentNode.insertBefore(newScript, thisScript.nextSibling);
};
(scripts || []).reverse().forEach(createScriptTag);
})(['example.com/js/script.js', 'example.com/js/form.js']);
</script>
Here is another method of solving this problem :
<script type="text/javascript">
window.onload = function () {
"use strict";
function js(n) {
var s = document.createElement('script');
s.setAttribute("type", "text/javascript");
s.setAttribute("src", n);
document.getElementsByTagName("head")[0].appendChild(s);
}
js("http://requirejs.org/docs/release/2.1.8/minified/require.js");
js("http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
js("http://www.example.com/form.js");
js("http://www.example.com/script.js");
};
</script>
This can also be used rather than the code explained in question.
i want to only trigger a page hit once a function has been triggered. so can i do the following?
<script type="text/javascript">
function gaCodeParser(parseGAcode){
if(parseGAcode == 'triggerGAcode'){
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxxx-xx']);
_gaq.push(['_trackPageview', '/success-page']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
}
else{
//do nothing
}
}
</script>
Why do you want to capture that ? google analytics will anyway give you efficient metrics like unique views, unique visitors and so on, if you try to fiddle around thier code you will only loose metrics provided by GA. if you still want to go ahead and fork what is given by GA you can still do so but please dont expect GA to give you all metrics.