This is the (default/official) JavaScript code for loading Disqus comments on a web page:
(CODE #1)
<script type="text/javascript">
var disqus_shortname = 'paulund';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
As I see it, the code does the HTTP request asynchronously; but that's not the point.
The thing is, I needed to make some changes to the code so that the comments are loaded only when the user scrolls down to the comments section, as in, lazy loading. And I've got two working methods to do it.
(CODE #2)
jQuery(document).ready(function($){
$('#comments').waypoint(function () {
var disqus_shortname = 'paulund';
$(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}, { offset: '100%', triggerOnce: true });
});
(CODE #3)
jQuery(document).ready(function($){
$('#comments').waypoint(function () {
var disqus_shortname = 'paulund';
$.ajax({
type: "GET",
url: "http://" + disqus_shortname + ".disqus.com/embed.js",
dataType: "script",
cache: true
});
}, { offset: '100%', triggerOnce: true });
});
Questions:
Apart from the obvious fact that I am now doing it with jQuery, is there any difference between what the codes #1 and #2, and #1 and #3, do? Could I possibly be doing something wrong, which I am completely missing?
Why don't the codes #2 and #3 work when started with $.noConflict();? (After all I found it in the docs as well.)
For instance, this doesn't do anything. (But gives an error in the browser console, "Uncaught TypeError: Cannot call method 'noConflict' of undefined.".)
$.noConflict();
jQuery(document).ready(function($){
$('#comments').waypoint(function () {
var disqus_shortname = 'paulund';
$.ajax({
type: "GET",
url: "http://" + disqus_shortname + ".disqus.com/embed.js",
dataType: "script",
cache: true
});
}, { offset: '100%', triggerOnce: true });
});
Nope, no difference. I would use method 3. $.noConflict should not have any effect if used the way you have it.
Uncaught TypeError: Cannot call method 'noConflict' of undefined. would mean that you've already used $.noConflict somewhere else.
There is no difference between the two, both are loading the script asynchronously. You can see for yourself by viewing the rendered script tag in the DOM explorer in your console. If you need it to load synchronously you could utilize the first method and set dsq.async = false;. If you are relying on it being loaded before performing some operation, consider adding your dependent operation into a onload callback of the script, that way it will be a non-blocking operation and keep your page loading fast:
var disqus_shortname = 'paulund';
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.onload = function(){
// dependent code goes here
}
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
Related
I have had the website for 3 years. This website is created by HTML, CSS, and JavaScript. I have made it by myself and there is always a WhatsApp icon at the bottom of the right. But 6 months ago, it disappeared. I looked up my code and there are no changes. How can I make my WhatsApp ıcon visible again?
Here is my code:
<script type="text/javascript">
(function () {
var options = {
whatsapp: "+9000000000", // Contact Number
call_to_action: "Merhaba, Size nasıl yardımcı olabilirim?",
position: "right",
};
var proto = document.location.protocol, host = "whatshelp.io", url = proto + "//static." + host;
var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = url + '/widget-send-button/js/init.js';
s.onload = function () { WhWidgetSendButton.init(host, proto, options); };
var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x);
})();
//</script>
The domain whatshelp.io is currently timing out, which is probably why the buttons are not working.
Based on archive.org, it appears at some point the site started to redirect to bothelp.io. However, updating the script to https://static.bothelp.io/widget-send-button/js/init.js returns a 404.
After some googling, I landed on this page: https://apps.shopify.com/whatshelp-chat-button
The description noted the following:
The GetButton widget (former WhatsHelp widget) takes website visitor directly...
Again, updated the script to https://static.getbutton.io/widget/bundle.js and success!
I then updated the configuration script you provided to the following (formatted for legibility):
<script type="text/javascript">
(function () {
var options = {
whatsapp: "+9000000000", // Contact Number
call_to_action: "Merhaba, Size nasıl yardımcı olabilirim?",
position: "right",
};
var proto = document.location.protocol,
host = "getbutton.io",
url = proto + "//static." + host;
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = url + '/widget-send-button/js/init.js';
s.onload = function () { WhWidgetSendButton.init(host, proto, options); };
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
})();
</script>
And saw the following:
I am trying to enable sign in with google on my site. The button works, syncs with my account, but I can not access the userId from google. This is what's in my head.
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
And this is where I'm trying to obtain the user Id. In the console I get the error message Uncaught ReferenceError: gapi is not defined. I thought I was calling gapi in the source above. Any help or suggestions would be much appreciated.
$('document').ready(function(){
var request = gapi.client.plus.people.get({
'userId' : 'me'
});
request.execute(function(resp) {
console.log('ID: ' + resp.id);
console.log('Display Name: ' + resp.displayName);
console.log('Image URL: ' + resp.image.url);
console.log('Profile URL: ' + resp.url);
});
});
Your code is calling gapi.client.plus.people.get method before loading the google api library https://plus.google.com/js/client:plusone.js. Hence you are getting gapi is not defined error.
Approach to work-
Why its not working?
We are calling https://plus.google.com/js/client:plusone.js asynchronously(non blocking) to improve the performance. With Async javascript file loading, you are not able to call the gapi method on body load.
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
</script>
To make the api call you first have to know javascript file is successfully loaded.
For this you have to call method using callback.
https://apis.google.com/js/client:plusone.js?onload=makeAPICall
Write an api request & execution it in the callback method to get data.
Check below example for this-
<html>
<head></head>
<body>
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="YOUR CLIENT ID.apps.googleusercontent.com"
data-cookiepolicy="single_host_origin"
data-scope="https://www.googleapis.com/auth/plus.login">
</span>
</span>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js?onload=signinCallback';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
document.getElementById('signinButton').setAttribute('style', 'display: none');
makeAPICall();
} else {
console.log('Sign-in state: ' + authResult['error']);
}
}
function makeAPICall(){
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function (resp){
console.log(resp);
if(resp.id){
console.log('ID: ' + resp.id);
}
if(resp.displayName){
console.log('Display Name: ' + resp.displayName);
}
if(resp.image && resp.image.url){
console.log('Image URL: ' + resp.image.url);
}
if(resp.url){
console.log('Profile URL: ' + resp.url);
}
});
});
}
</script>
</body>
</html>
Conclusion: Calling javascript API before loading the asynchronously client library.
To avoid "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.". Call makeAPICall() method only when user is logged in not on every request.
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
I'm using opencart 1.5.5.1.
On the products pages I've already successfully changed the "Review" tab with a discussion tool by Disqus! and it works great.
But my website is dual language italian/english and I would like the users to read the discussion in the language they've chosen.
So I've created two differents disqus id's (two independent discussion boards).
On my product.tpl I had to insert their javascript that comes with a variable like:
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'xxxxxxxxxx';
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
I would like to make the variable disqus_shortname to depend on language code given on the session.
As long as I understand I can get it by php with
$this->session->data['language']
or
$this->language->get('code')
but here we are talking about js!
How can I tell this script the statement if?
I need something like
if $this->language->get('code') == 'it' { var disqus_shortname = 'xxxxxxxxxxitalian'; }
else { var disqus_shortname = 'xxxxxxxxxxenglish'; }
Check whether you register a disqus shortname for your website on Disqus.
disqus_shortname
Tells the Disqus service your forum's shortname, which is the unique
identifier for your website as registered on Disqus. If undefined, the
Disqus embed will not load.
To load different language on the page,use
var disqus_config = function () {
this.language = "ru";
};
code like:
<?php
$language = ( $this->language->get('code') == 'it' )? 'it' : 'en';
?>
<script>
var disqus_config = function () {
this.language = "<?php echo $language; ?>";
};
http://help.disqus.com/customer/portal/articles/466249-can-disqus-be-loaded-in-different-languages-per-page-
In Your controller You would have to propagate the language code to the template (edit catalog/controller/product/product.php file) - add this:
$this->data['language_code'] = $this->language->get('code');
Then edit the template file this way (catalog/view/theme/<YOUR_THEME>/template/product/product.tpl):
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'xxxxxxxxxx<?php echo $language_code; ?>'; // here the mojo is done...
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script');
dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
On thirdpartydomain.com I want to embed a simple <script> tag that pulls in a script from mydomain.com/myscript.js, which simply creates a little <div> and pulls partial page content from mydomain.com/mypage.htm.
Here's the script, adapted from: How to embed Javascript widget that depends on jQuery into an unknown environment
var myEmbedId = '12345';
var myEmbedContainerId = 'myEmbedContainer_' + myEmbedId;
document.write('<div id="' + myEmbedContainerId + '">IF ALL GOES WELL, THIS TEXT WILL BE REPLACED WITH MYPAGE.HTM CONTENTS');
document.write('</div>');
(function (window, document, version, callback) {
var j, d;
var loaded = false;
if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://mydomain.com/jquery-1.4.1.min.js";
script.onload = script.onreadystatechange = function () {
if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
callback((j = window.jQuery).noConflict(1), loaded = true);
j(script).remove();
}
};
document.documentElement.childNodes[0].appendChild(script)
}
})(window, document, "1.3", function ($, jquery_loaded) {
$(document).ready(function () {
alert('jquery loaded!');
var myRefreshUrl = 'http://mydomain.com/mypage.htm';
alert('refreshing from ' + myRefreshUrl);
$.get(myRefreshUrl, function(data){
var returnData = data;
alert('return data: ' + data);
$('#' + myEmbedContainerId).html(data); });
alert('load complete v2');
});
});
In IE, I get an Access Denied error from Javascript; in Firefox I just get no data returned.
What's wrong with this?
You cannot create an AJAX request to a different domain from the one that is hosting the current window context.
To pull off what you're describing, you can do something like:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://mydomain.com/dynamic.js?data=somepage.htm';
someContainer.appendChild(script);
Within that dynamic.js, you can wrap the HTML contents in a document.write(). The net effect is the same as inserting the result of the AJAX request at the same point in the DOM.