Reputation: 1550
(function () {
function callbackF(data) {
eval(data.script);
}
window.onload = function () {
if (url.indexOf('.html') > 0) {
var gt_widget_id = document.createElement('div');
gt_widget_id.setAttribute('id', 'gt_widget_0');
var comments = document.getElementById('comments');
comments.parentNode.insertBefore(gt_widget_id, comments);
var comments = document.getElementById('comments');
var script = document.createElement('script');
script.setAttribute('src', "http://dev.example.com/wp/wpregister.asp?callback=callbackF&ver=2.5&url=" + encoded_url);
script.setAttribute("type", "text/javascript");
script.setAttribute("id", "grazit_script");
document.getElementById("gt_widget_0").parentNode.appendChild(script);
}
}
})();
The html is not relevant to the question, the tag does get appended and json return is just after the call, the console tells me that callbackF is undefined? why is that?
Upvotes: 0
Views: 102
Reputation: 1038770
why is that?
Because you need to define your callbackF
function outside of the closure:
function callbackF(data) {
eval(data.script);
}
(function () {
window.onload = function () {
if (url.indexOf('.html') > 0) {
var gt_widget_id = document.createElement('div');
gt_widget_id.setAttribute('id', 'gt_widget_0');
var comments = document.getElementById('comments');
comments.parentNode.insertBefore(gt_widget_id, comments);
var comments = document.getElementById('comments');
var script = document.createElement('script');
script.setAttribute('src', "http://dev.example.com/wp/wpregister.asp?callback=callbackF&ver=2.5&url=" + encoded_url);
script.setAttribute("type", "text/javascript");
script.setAttribute("id", "grazit_script");
document.getElementById("gt_widget_0").parentNode.appendChild(script);
}
}
})();
Alternatively you could define your callbackF
function on the window
scope so that it is accessible from the outside of the closure:
(function () {
window.callbackF = function(data) {
eval(data.script);
};
window.onload = function () {
if (url.indexOf('.html') > 0) {
var gt_widget_id = document.createElement('div');
gt_widget_id.setAttribute('id', 'gt_widget_0');
var comments = document.getElementById('comments');
comments.parentNode.insertBefore(gt_widget_id, comments);
var comments = document.getElementById('comments');
var script = document.createElement('script');
script.setAttribute('src', "http://dev.example.com/wp/wpregister.asp?callback=callbackF&ver=2.5&url=" + encoded_url);
script.setAttribute("type", "text/javascript");
script.setAttribute("id", "grazit_script");
document.getElementById("gt_widget_0").parentNode.appendChild(script);
}
}
})();
Upvotes: 1