Multiple Javascript Asynchronously Loading in a Page - javascript

<script type="text/javascript">
function loadScript(scriptpath) {
var s = document.getElementsByTagName('script')[0];
var ss = document.createElement('script');
ss.type = 'text/javascript';
ss.async = true;
ss.src = scriptpath;
s.parentNode.insertBefore(ss, s);
}
loadScript('compressed1.js');
loadScript('compressed2.js');
</script>
but i am getting error that SS is not defined can somebody help me with above coding?

var ssa
Keep variable names consistent. It's usually a good idea to give meaningful names like newScript

Related

Google Custom Search is adding %20 in search URL and Query

I have created a google custom search for my website as below but when i search 2-3 keywords it replaces the spaces with %20 and shows no results:
Result Page and Query
Search Box Code:
<script>
(function() {
var cx = '44444:orudazwgyxa';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchbox-only></gcse:searchbox-only>
Search result code:
<script>
(function() {
var cx = '44444:orudazwgyxa';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
</script>
<gcse:searchresults-only linktarget="_parent"></gcse:searchresults-only>
I don't want %20 in my query instead of spaces but i want to show the keywords as it is. And it should show the result for the searched keywords.
Thanks
It seems the solution to the bad results is taking the "www" out of our target URL for the results page.
Sounds goofy to me, but hey, it worked.
So, if anyone else is having the same problem, check your result page URL target and remove the www from it
So instead of: http://www.yourwebsite.com/search_results.html
use: http://yourwebsite.com/search_results.html
And, then it will work!

Javascript append string dynamically to script element

How do I append the following variable within my html (as part of script tag).
var x = '-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n;';
I am getting an invalid token error with the below code;
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.innerHTML = "var x = '-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbjEcMBoGA1UEAxMTU29mdGZvcnVtIFB1YmxpYyBDQTE\nODQzMzhaFw0yMj45645gNVBAYTAktSMREwDwYDVQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n;';";
$("body").append( script );
You need to escape the carriage returns. Also as #maxzoom suggests, you probably want to use innerText rather than innerHTML.
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = "var x = '-----BEGIN CERT\\nMIIDvTCCAqWgAsdfsdfTAktS\\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\\naXR5IFJORCBEaXZpc2lvbjEcMBoGA1UEAxMTU29mdGZvcnVtIFB1YmxpYyBDQTE\\nODQzMzhaFw0yMj45645gNVBAYTAktSMREwDwYDVQQKDAhq\\ncG1vcmdhbjER\\n-----END CERT-----\\n;'; console.log(x);";
$("body").append(script);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here from the inspector is it working in action...
To handle embedded expressions such as new line character \n in a string you could use Template literals notation as below:
var script = document.createElement('script');
script.type = 'text/javascript';
var content = "var x = `-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbjEcMBoGA1UEAxMTU29mdGZvcnVtIFB1YmxpYyBDQTE\nODQzMzhaFw0yMj45645gNVBAYTAktSMREwDwYDVQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n`;";
content += "console.log(x);";
script.innerHTML = content;
$("body").append(script);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
When viewing generated source in browser the script is present in body element:
You should try this way:
var x = '-----BEGIN CERT\nMIIDvTCCAqWgAsdfsdfTAktS\nMR4wHAYDVQQKExVTb2Z0Zm9ydW0gQ29yc45656b24xHjAcBgNVBAsTFVNlY3Vy\naXR5IFJORCBEaXZpc2lvbjEcMBoGA1UEAxMTU29mdGZvcnVtIFB1YmxpYyBDQTE\nODQzMzhaFw0yMj45645gNVBAYTAktSMREwDwYDVQQKDAhq\ncG1vcmdhbjER\n-----END CERT-----\n;'
var script = `<script type="text/javascript">${x}</script>`
$("body").append(script);

Two custom searches in same page disables search predictions

While using different styles for larger displays and mobiles, I was forced to insert two google custom search boxes in same page. The search still works perfectly but the issue is that search predictions are no longer available after inserting the second search box.
(function() {
var cx = '*****************:**********';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
The same code is using twice in the same page(especially repeated id usage) which causes the conflict I think. Already referred similar posts 'How to have multiple Google Custom Search field on the same page' and 'Multiple GCSE's on page at one time', but those are not solutions for the situation which I'm facing. How to enable both search boxes in same page work in a similar manner without causing conflict?
I'm currently experimenting with this. Getting 2 cse's with a different cx on the same page isn't that hard, but can't get the suggestions working. The v2 control api method description isn't very clear.
But with a single cx you can just do this:
html:
<div id="first"></div>
<br/>
<div id="second"></div>
js:
var renderSearchElement = function() {
google.search.cse.element.render({
div: "first",
tag: 'search'
});
google.search.cse.element.render({
div: "second",
tag: 'search'
});
};
var myCallback = function() {
if (document.readyState == 'complete') {
renderSearchElement();
} else {
google.setOnLoadCallback(renderSearchElement, true);
}
};
window.__gcse = {
parsetags: 'explicit',
callback: myCallback
};
var loadElements = function() {
var cx = '*****************:**********';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
}
loadElements();
demo:
https://jsfiddle.net/501g48d4/
CSE v2 control API and render params: https://developers.google.com/custom-search/docs/element

How to make goal completion work on hashchange?

I have an AngularJS webapp where there are no separate pages.
I have set up a goal completion so that there's a code that is triggered by a javascript event,
and it has the following structure:
function call_completion(){
window.google_conversion_id = 973404965;
window.google_conversion_language = "en";
window.google_conversion_format = "1";
window.google_conversion_color = "ffffff";
window.google_conversion_label = "doGHCLPK2wkQpfaT0AM";
window.google_conversion_value = 1.000000;
window.google_remarketing_only = false;
var s = document.createElement('script');
s.type = "text/javascript";
s.src = '//www.googleadservices.com/pagead/conversion.js';
document.body.appendChild(s);
}
Yet, I can't see any completions registered in Google Analytics. What could be the problem?
Is this the correct way to do it? Is there perhaps some nifty plugin that gets this problem right?
UPDATE:
For the new Universal Analytics, there is a plugin called angular-ga.
It eliminates the whole question.
You shouldn't append the script to your view, since it won't be executed.
You should use this:
$.getScript( "http://www.googleadservices.com/pagead/conversion.js" );
To get the script working on that page and execute it.
Hope this helps :)
The <noscript> part also has to be included.
Something like this:
$('body')
.append('\
<!-- Google Code for Subscriptions Conversion Page -->\n\
<script type="text/javascript">\n\
/* <![CDATA[ */\n\
var google_conversion_id = 973404965;\n\
var google_conversion_language = "en";\n\
var google_conversion_format = "1";\n\
var google_conversion_color = "ffffff";\n\
var google_conversion_label = "doGHCLPK2wkQpfaT0AM";\n\
var google_conversion_value = 1.000000;\n\
var google_remarketing_only = false;\n\
/* ]]> */\n\
</script>\
');
$('body')
.append('<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">')
.append($('<noscript>')
.append($('<div style="display:inline;">')
.append('<img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/973404965/?value=1.000000&label=doGHCLPK2wkQpfaT0AM&guid=ON&script=0"/>')
)
);

How to pass back a unique ID with JavaScript or PHP?

I need to pass back a unique ID in place of "INSERT+ORDER+ID" for when a user clicks on our "Request Information" button to better track our visitors. Does anyone know how I can accomplish this? Any help would be much appreciated, thanks!
<script type="text/javascript">
var _qevents = _qevents || [];
(function() {
var elem = document.createElement('script');
elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") +
".quantserve.com/quant.js";
elem.async = true;
elem.type = "text/javascript";
var scpt = document.getElementsByTagName('script')[0];
scpt.parentNode.insertBefore(elem, scpt);
})();
_qevents.push(
{qacct:"p-yeADJca0S9FXE",labels:"_fp.event.Request Information Confirmation
Page",orderid:"INSERT+ORDER+ID"}
);
</script>
<noscript>
<img src="//pixel.quantserve.com/pixel
/p-yeADJca0S9FXE.gif?labels=_fp.event.Request+Information+Confirmation+Page&
orderid=INSERT+ORDER+ID" style="display: none;" border="0" height="1" width="1" alt="Quantcast"/>
</noscript>
assuming you mean a random unique ID,
for the javascript event tracking this should work:
// function to generate random id in js
function getRandomId() {
var id = +new Date() + Math.random();
return id.toString().replace('.','');
}
var btnReqInfo = document.getElementById('request_information_btn');
// bind the click on button
btnReqInfo.addEventListener('click', function() {
// track the event
_qevents.push({ qacct:"p-yeADJca0S9FXE", labels: "_fp.event.Request Information ConfirmationPage",orderid: getRandomId() });
, false);
About the content in the noscript tag, you can't do it with static html of course so you have to put in the context of your template (in the php file), something like this that generates a unique ID and then echo it in place of your placeholder.
Since I'm in the mood for structuring and cleaning, I took the liberty of refactoring a bit the code, in case, you can replace all your script with this (assuming you're using plain js (vanilla) and html 5):
<script>
var _qevents = _qevents || [];
(function() {
var
init = function() {
loadScript();
bindUi();
},
loadScript = function() {
var elem = document.createElement('script');
elem.src = (document.location.protocol == "https:" ? "https://secure" : "http://edge") + ".quantserve.com/quant.js";
elem.async = true;
elem.type = "text/javascript";
var scrpt = document.getElementsByTagName('script')[0];
scrpt.parentNode.insertBefore(elem, scrpt);
},
bindUi = function() {
var btnReqInfo = document.getElementById('request_information_btn');
btnReqInfo.addEventListener('click', track.order, false);
},
track = {
order: function() {
_qevents.push({ qacct:"p-yeADJca0S9FXE", labels: "_fp.event.Request Information ConfirmationPage", orderid: utils.getRandomId() });
}
},
utils = {
getRandomId : function() {
var id = +new Date() + Math.random();
return id.toString().replace('.','');
}
};
init();
})();
</script>
I would suggest using an AJAX call that is binded to the onclick event or .click if you're using JQuery
The AJAX call would hit a PHP script or call whatever you're using for analytics.

Categories