The recommendation of the open source web analysis software Piwik is to put the following code at the end of the pages you want to track, directly before the closing </body> tag:
<html>
<head>
[...]
</head>
<body>
[...]
<!-- Piwik -->
<script type="text/javascript">
var pkBaseURL = (("https:" == document.location.protocol) ? "https://piwik.example.com/" : "http://piwik.example.com/");
document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
</script><script type="text/javascript">
try {
var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 4);
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
} catch( err ) {}
</script><noscript><p><img src="http://piwik.example.com/piwik.php?idsite=4" style="border:0" alt="" /></p></noscript>
<!-- End Piwik Tracking Code -->
</body>
</html>
Under the following assumptions:
https is never used
we don't care that the page loads slower because the script is loaded before the DOM
is it okay to convert the above to the following:
HTML file:
<html>
<head>
[...]
<script src="http://piwik.example.com/piwik.js" type="text/javascript"></script>
</head>
<body>
[...]
<noscript><p><img src="http://piwik.example.com/piwik.php?idsite=4" style="border:0" alt="" /></p></noscript>
</body>
</html>
Custom Javascript file with jQuery:
$(document).ready(function() {
try {
var piwikTracker = Piwik.getTracker("http://piwik.example.com/piwik.php", 4);
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
}
catch(err) {
}
}
Are there any differences?
You are deferring the tracking until the page is fully loaded. Inline Javascript is executed when the browser finds it, so you'll have different number of visits depending on where you call piwikTracker.trackPageView();. The latter you call it, the lesser number of visits/actions will be counted.
Now, what do you consider a visit/action? If a user click on a link on your page, before the page fully loads, do you consider it a visit?
Related
I'd like to load and execute an external javascript file (Google Adwords's conversion script) only if a condition is met. Similar questions have already been asked, I've tried their solutions but it didn't work. I've the following code :
<script>
$(function() {
if ([condition]) {
$.getScript('//www.googleadservices.com/pagead/conversion.js');
}
});
</script>
The script is loaded but isn't executed. How do I do to execute it ?
I've tried to change getScript() with
var script = document.createElement("script" );
script.setAttribute("src", "//www.googleadservices.com/pagead/conversion.js" );
document.getElementsByTagName("head" )[0].appendChild(script);
but it didn't work as well.
Thanks !
#VLAS: Oops pasted the wrong thing, corrected
#ejay_francisco: I already tried to create the script tag and append it to the head but it doesn't work
#Barar: I mean the page downloads the script file but doesn't execute it. Yes, if you want the full code :
<!-- Google Code for Formulaire Contact Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = [...];
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "[...]";
var google_remarketing_only = false;
/* ]]> */
</script>
<!-- <script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"></script> -->
<script type="text/javascript" src="//code.jquery.com/jquery.min.js"></script>
<script>
$(function() {
if ([condition]) {
$.getScript('//www.googleadservices.com/pagead/conversion.js');
$("#google_conversion").attr('src','//www.googleadservices.com/pagead/conversion/[...]/?label=[...];guid=ON&script=0');
}
});
</script>
<div style="display:inline;">
<img id="google_conversion" height="1" width="1" style="border-style:none;" alt="" src="#"/>
</div>
In the long run you'd be better off using the proper asynchronous version of the adwords conversion script I think as it has been built specifically to handle these sorts of things. This way avoids any encoding mistakes and is easier to read and maintain.
So, based on this here is what I reckon you'd want (although I am no jQuery expert - I prefer to use standard javascript but hey each to their own):
<head>
<!-- Add the async conversion script as usual - use async if you want --->
<script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion_async.js" charset="utf-8"></script>
</head>
<!-- the rest of your site HTML and code -->
<script>
$(function() {
if ([condition]) {
window.google_trackConversion({
google_conversion_id: "[...]",
google_conversion_language: "en",
google_conversion_format: "3",
google_conversion_color: "ffffff",
google_conversion_label: "[...]",
google_conversion_value: 0,
google_remarketing_only: false
});
}
});
</script>
Try This:
<script type="text/javascript">
$(document).ready(function(){
if ([condition]) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.googleadservices.com/pagead/conversion.js";
document.getElementsByTagName("head")[0].appendChild(script);
}
});
</script>
Try this:
$(function() {
if ([condition]) {
$.getScript('//www.googleadservices.com/pagead/conversion.js', function() {
$("#google_conversion").attr('src','//www.googleadservices.com/pagead/conversion/[...]/?label=[...];guid=ON&script=0');
});
}
});
This doesn't set the src of #google_conversion until after the conversion.js script is loaded. If there's a dependency, you need to do them in the right order. You were doing this first, because $.getScript is asynchronous.
I have a bunch of web pages where I have an identical construct:
<html>
<head>
<script src="sorttable.js"></script>
<noscript>
<meta http-equiv="refresh" content="60">
</noscript>
<script type="text/javascript">
<!--
var sURL = unescape(window.location.pathname);
function doLoad()
{
setTimeout( "parent.frames['header_frame'].document.submitform.submit()", 60*1000 );
}
function refresh()
{
window.location.href = sURL;
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.replace( sURL );
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.reload( true );
}
//-->
</script>
</head>
<body>
.
.
.
<script type="text/javascript">
window.onload = function() { sorttable.innerSortFunction.apply(document.getElementById("OpenFace-2"), []); doLoad(); }
</script>
</body>
</html>
This works perfectly in every page except for one, where when the onload function runs it cannot find the sorttable code (which is loaded from sorttable.js up at the top). All these pages are part of the same application and are all in the same dir along with the js file. I do no get any errors in the apache log or the js console until that page loads, when I get:
sorttable.innerSortFunction is undefined
I can't see what makes this one page different. Can anyone see what is wrong here, or give me some pointers on how I can debug this further?
The code I pasted in is from the source of the page where it does not work, but it is identical as the pages where it does work.
Looks like on that page the table with id OpenPhace-2 by which you try to sort have no needed class: sortable
The function innerSortFunction of sorttable object will be present only if there is any table with sortable class exists.
My Javascript/html code looks like following which works great and shows country name in Part 1 below.
When i am trying to convert the code in .JS file it doesnt work means doesnt shows the country name in Part 2.. not sure what is wrong in the code
Part 1
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
var strip, strcountry, strcity, strregion, strlatitude, strlongitude, strtimezone
function GetUserInfo(data) {
strip = data.host; strcountry = data.countryName;
}
$(function ()
{
BindUserInfo();
})
function BindUserInfo()
{
document.getElementById('lblCountry').innerHTML = strcountry;
}
</script>
<script type="text/javascript" src="http://smart-ip.net/geoip-json?callback=GetUserInfo"></script>
</head>
<body>
We Ship To <a id="lblCountry"/>
</body>
Part 2
// JavaScript Document
document.write("<script src='http://code.jquery.com/jquery-1.8.2.js' type='text/javascript'></script>");
var strip, strcountry, strcity, strregion, strlatitude, strlongitude, strtimezone
function GetUserInfo(data) {
strip = data.host; strcountry = data.countryName;
}
$(function ()
{
BindUserInfo();
})
function BindUserInfo()
{
document.getElementById('lblCountry').innerHTML = strcountry;
}
document.write("<script type='text/javascript' src='http://smart-ip.net/geoip-json?callback=GetUserInfo'></script>");
Here is the HTML of PArt 2
<head>
<title>Get User Details IP Address, city, country, state, latitude, longitude </title>
<script src="test.js" type="text/javascript"></script>
</head>
<body>
We Ship To <a id="lblCountry"/>
</table>
Include the jQuery reference as a real script tag in your HTML still - and remove the document.write.
Also ; on the end of your var list... Perhaps.
Your <head> tag should be
<head>
<title>Get User Details IP Address, city, country, state, latitude, longitude
</title>
<script src='http://code.jquery.com/jquery-1.8.2.js' type='text/javascript'>
</script>
<script src="test.js" type="text/javascript"></script>
</head>
As Paul notes document.write is deprecated. You should always try to include <script> tags rather than manipulating the DOM. I think that the way you were doing it would mean that the jQuery code in your file would be executing before jQuery had loaded - due to the fact that you are writing the tag directly to the DOM immediately before your code. So there will not have been time to parse it. I would think that this code would have raised an error in fact.
I'm using HTML publisher in hope to have a html page with some javascript codes running on hudson. The HTML code is like this:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../stringformat.js"></script>
<script type="text/javascript">
......
sql=String.format("/.csv? select from table where exchange=`ABC......")
</script>
</head>
However, after a successful build, my html page doesn't show what it suppose to, and as I check the error console, it says
Error: TypeError: String.format is not a function
I have put my stringformat.js into the top folder, as the HTML publisher doesn't seem to allow the file to contain anything other than HTML files.
Can anyone tell me why the String.format is not loaded properly? Thanks!
PS: stringformat.js is the file i got from
http://www.masterdata.se/r/string_format_for_javascript/
The code should be working properly as this piece of code works outside the hudson
try code:
<html>
<head>
<title>String format javascript</title>
<script type="text/javascript">
String.format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
var _myString = String.format("hi {0}, i'am {1}","everybody", "stackoverflower");
function show(){
alert(_myString);
}
</script>
</head>
<body>
<input type="button" name="btnTest" id="btnTest" value="Test string format" onclick="show();" />
</body>
</html>
This is how I am calling the JavaScript function in my HTML page:-
<script type="text/javascript" src="imagerollover.js"></script>
</script>
<script type="text/javascript">
//Following function should be called at the end of the page:
imagerollover();
</script>
</head>
<body>
.
.
.
this is my imagerollover.js:-
function imagerollover(){
var allimages=document.getElementsByTagName("img")
var preloadimages=[]
for (var i=0; i<allimages.length; i++){
if (allimages[i].getAttribute("data-over")){ //if image carries "data-over" attribute
preloadimages.push(new Image()) //preload "over" image
preloadimages[preloadimages.length-1].src=allimages[i].getAttribute("data-over")
allimages[i].onmouseover=function(){
this.src=this.getAttribute("data-over")
}
allimages[i].onmouseout=function(){
this.src=this.getAttribute("data-out")
}
} //end if
} //end for loop
}
//Usage: Call following function at the end of the page:
//imagerollover()
Image tags:
<img src="knitting1.jpg"
data-over="knitting2.jpg"
data-out="knitting1.jpg"
alt="Logo" width="400px" height="90" align="middle" />
Also, both images knitting1.jpg and knitting2.jpg exist in my site's root folder. I don't know what is wrong.
I placed an alert inside imagerollover.js file in the beginning. It is getting called but it is not showing any roll over effect. Why?
You need to run this onload - your images tags are not yet available to the script when you execute the function - you are not actually following the instruction of the script which should have been placed at the end of the page or in my suggestion in the onload
<head>
<script type="text/javascript" src="imagerollover.js"></script>
</script>
<script type="text/javascript">
window.onload=function()
//Following function should be called at the end of the page OR on window.onload!
imagerollover();
}
</script>
</head>