Dynamic script not firing - javascript

I am trying to add a github gist to my webpage on the click of a button however the gist is not appearing.
function createGist(gistId = "bd10e846c6eae4419c3041f3da1b82a0"){
var script = document.createElement("script");
script.src = "https://gist.github.com/snakifyanswers/" + gistId + ".js";
document.body.appendChild(script) }
I am left with nothing there even though in inspect element I can see the script object.

Related

Firing JavaScript generated link issue

I have issues firing this link (that triggers a script from Chargebee) when is added dynamically via JavaScript. When it's added directly in html it works normally.
The entire generated link is appearing correctly (populated with the variants) in browser when inspected just it doesn't fire.
Here are the pieces I have related to this:
The JavaScript part:
var checkout = document.getElementById("checkout");
var link = '<a href="javascript:void(0)" data-cb-type="checkout"' + data-cb-1 + data-cb-2 + data-cb-3'>Order</a>';
checkout.innerHTML = link;
A simple div:
<div id="checkout"></div>
The script from chargebee:
<script src="https://js.chargebee.com/v2/chargebee.js" data-cb-site="site-name"></script>
Once you've loaded chargebee.js script it starts to look for a tag a with specific data-cb attributes. The script does it one time only. If the tag a did not exist in the DOM then, the script does nothing. When you add the tag a later that makes no effect at all, because a "discovery phase" is over.
If you want to have more control over chargebee initialisation process, you should go for "Checkout via API" option provided by the developers.
P.S. There are two hacky solutions:
You may load Chargebee script after adding tag a to the DOM.
function loadChargebee() {
var script = document.createElement("script");
script.src = "https://js.chargebee.com/v2/chargebee.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
}
var checkout = document.getElementById("checkout");
var link = '<a href="javascript:void(0)" data-cb-type="checkout"' + data-cb-1 + data-cb-2 + data-cb-3'>Order</a>';
checkout.innerHTML = link;
loadChargebee(); // <=== add Chargebee.js
Leave the tag a in the DOM, load the script as usual but modify data attributes as needed after page load:
<a id="beecheckout" href="javascript:void(0)" data-cb-type="checkout" data-cb-1="" data-cb-2="" data-cb-3="">Order</a>
document.getElementById('beecheckout').setAttribute('data-cb-1','new data value');

Javascript widget inside JQuery

We are using the Ning platform, and in order to add a new container DIV underneath the blog content (but before the comment section), we added the following before the body tag:
<script type="text/javascript">
if (typeof(x$) != 'undefined') {
x$("DIV.xg_module.xg_blog.xg_blog_detail.xg_blog_mypage.xg_module_with_dialog").after('<div>CONTENT GOES HERE </div>');
}
else{
}
</script>
However, then the content we need to load is javascript from an affiliate program, who sent us this code to add into that div:
<div style="width:750px;">
<div style="border-bottom:1px solid #FFFFFF;color:#FFFFFF;font-family:Arial,Helvetica,sans-serif;font-size:22px;font-weight:bolder;margin-bottom:10px;padding-bottom:2px;text-transform:uppercase;">From Around the Web</div>
<script type='text/javascript'>
var _CI = _CI || {};
(function() {
var script = document.createElement('script');
ref = document.getElementsByTagName('script')[0];
_CI.counter = (_CI.counter) ? _CI.counter + 1 : 1;
document.write('<div id="_CI_widget_');
document.write(_CI.counter+'"></div>');
script.type = 'text/javascript';
script.src = 'http://widget.crowdignite.com/widgets/29949?_ci_wid=_CI_widget_'+_CI.counter;
script.async = true;
ref.parentNode.insertBefore(script, ref);
})(); </script>
</div>
And obviously, that does not work.
THE QUESTION: is there a better way to do this? Is it just a matter of all the conflicting 's and "s? Is there an easier way to format this or output it? Is it failing because it's simply not loading the javascript after the JQuery has already run post-page load? I have been trying different things and none seem to work and my eyes are ready to pop out of their sockets because I know there's something stupid I'm missing, so I thought I'd get some more eyes on it.
Thanks for any help/ideas/suggestions.
Try appending your new script element to the head element on your page. Most dynamic script loaders do this.
See Ways to add javascript files dynamically in a page for an example.

How to implement Facebook conversion tracking onclick or when there's no separate 'Thank you' page

Trying to implement Facebook conversion tracking within a Facebook Tab. You can view the page here http://www.facebook.com/StChristophersFellowship/app_366591783429546 the issue is a separate page is not run once the form has been submitted. Can I make a section of javascript run but ONLY onclick of the submit button, I think it also has the be injected into the head of the HTML doc.
I found this answer to running Javascript from a link or click - Will this method work if I call the tracking/conversion code from a separate JS doc?
Any help would be greatly appreciated - Thanks!
"I have to agree with the comments above, that you can't call a file, but you could load a JS file like this, I'm unsure if it answers your question but it may help... oh and I've used a link instead of a button in my example...
<a href='linkhref.html' id='mylink'>click me</a>
<script type="text/javascript">
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "Public/Scripts/filename.js.";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>"
I tried using Nicolás solution but the conversion was never verified.
However I found an article (archived version) describing a technique that worked instantly, using the URL from <noscript><img src="..." /></noscript>.
Place an element on your page like:
<div id="fb_pixel"></div>
Then declare these CSS rules for your conversions, changing the background-image for the <noscript> URL found in your own tracking code.
#fb_pixel { display:none; }
.fb_conversion
{
background-image: url('https://www.facebook.com/offsite_event.php?id=33333333333&value=0&currency=USD');
}
When you want the tracking to occur (e.g. upon AJAX form submission), you add the fb_conversion class to the <div> using JavaScript. For instance, with jQuery:
$("#fb_pixel").addClass("fb_conversion");
This will make the browser load the image, thus tracking your conversion.
I had a similar issue, I solved it putting the AJAX call on the tacking callback. As follows:
$(function () {
$('#btnSend').click(facebookTrackingSendClick);
});
function facebookTrackingSendClick(e) {
e.preventDefault();
var clickedElement = this;
var fb_param = {};
fb_param.pixel_id = '123';
fb_param.value = '0.00';
fb_param.currency = 'BRL';
(function () {
var fpw = document.createElement('script');
fpw.async = true;
fpw.src = '//connect.facebook.net/en_US/fp.js';
fpw.onload = function () {
// Callback here.
};
var ref = document.getElementsByTagName('script')[0];
ref.parentNode.insertBefore(fpw, ref);
})();
}

How to get text inside span, and use it into other script

let say..
<span id="Singer">Bieber</span>
I know by using DOM I can duplicate 'Bieber' to anywhere..
<script>
x=document.getElementById("Singer");document.write("<span>" + x.innerHTML + "</span>");</script>
..but id doesn't seems working when I want to insert the DOM script into the script below. Is there any way to put 'Bieber' into the script below?
<script language=JavaScript src="http://lyricfind.rotator.hadj7.adjuggler.net/servlet/ajrotator/275968/0/vj?z=lyricfind&dim=35518&click=&kw=<I WANT TO PUT BIEBER HERE>"></script>
The problem you have is the browser will be firing off the request for the script before it is able to access the span element. It could be done by dynamically inserting the script tag after the span is read:
window.onload = function(){
var x = document.getElementById("Singer");
var s = document.createElement("script");
s.src = "http://lyricfind.rotator.hadj7.adjuggler.net/servlet/ajrotator/275968/0/vj?z=lyricfind&dim=35518&click=&kw=" + encodeURIComponent(x.innerHTML);
s.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(s);
};
This assumes your page has a <head> section. If not, you could append to the body instead.

How in insert dynamic JavaScript tag into iframe

FINAL UPDATE: The second code block is working--I just miss-typed the URL.
I'm trying to place a dynamically created script into an iframe. I can access the head of the iframe, but it doesn't seem to accept the append request. The console log call returns the head tag, and the following append of text into the body works fine. I've also tried appending the script tag to the body. (note: the script tag is not on the same domain, so I've avoided using getScript or ajax).
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//cross-domain.com/script.js";
console.log($(this).contents().find("head")); // outputs: [<head></head>]
$(this).contents().find("head").append(script); // doesn't work
$(this).contents().find("body").append(script); // doesn't work
$(this).contents().find("body").append("Test"); // works
}).appendTo("#content");
});
Here is the new version that successfully appends the script based upon the suggestion below, but the script doesn't evaluate (as tested by a simple alert). Plus, another oddity: the "working" icon displays for about 15 seconds and the status (in chrome) says "retrieving..." Eventually it stops, but nothing happens.
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//cross-domain.com/script.js";
console.log($(this).contents().find("head"));
$(this).contents().find("head")[0].appendChild(script);
$(this).contents().find("body").append("Test");
}).appendTo("#content");
});
Update: When the cursor icon finally finishes working (about 10 seconds, which is odd because it's a local server with one line of code), I get this message in the Chrome console (it's in all red with a red circle "X" icon next to it):
GET http://cross-domain.com/script.js
(anonymous function)temp.html:16
jQuery.event.dispatchjquery-1.7.1.js:3261
jQuery.event.add.elemData.handle.eventHandlejquery-1.7.1.js:2880
jQuery.fn.extend.appendjquery-1.7.1.js:5771
jQuery.fn.extend.domManipjquery-1.7.1.js:5973
jQuery.fn.extend.appendjquery-1.7.1.js:5769
jQuery.each.jQuery.fn.(anonymous function)jquery-1.7.1.js:6162
(anonymous function)temp.html:18
jQuery.Callbacks.firejquery-1.7.1.js:1049
jQuery.Callbacks.self.fireWithjquery-1.7.1.js:1167
jQuery.extend.readyjquery-1.7.1.js:435
DOMContentLoaded
See this answer https://stackoverflow.com/a/3603496/220299
It may in fact be working, but the script tag is just not visible.
Try this.
$(document).ready(function() {
$('<iframe></iframe>', {
name:"contentFrame"
,id:"contentFrame"
}).css("height", 300).css("width", 500).load(function() {
$(this).contents().find("head").append('<scr' + 'ipt type="text/javascript" src="//cross-domain.com/script.js"></scr' + 'ipt>');
}).appendTo("#content");
});

Categories