I am making a cross domain request using script tag hack and jsonp. In the callback function, I want to write the data received to DOM using document.write().
I know that I should use appendChild/innerHTML instead of doc.write(). My constraint is I do not have a class/id hook to the element I want to write to. I can only rely on document.write() to write "in place".
Following code is included in HTML div in a script tag.:
function request_jsonp(){
var script = document.createElement('script');
var server_path = 'http://somedomain.com/?q=querystring&callback=request_callback';
script.setAttribute('src', server_path);
document.getElementsByTagName('head')[0].appendChild(script);
console.log('data requested');
// document.write('hello world'); // this gets written
}
function request_callback(data){
console.log('data received');
document.write(data);
}
request_jsonp();
window.onload = function(){
console.log('onload fired');
}
/*
above code prints
data requested
data received
onload fired
*/
Basically document.write does not work even with a static string inside the callback function. I thought that if document.write is called before onload, it inserts text in the page as noted here JavaScript and HTML Script Tags
What is preventing the document.write() to write to DOM? Also, is there a better approach to do this?
Array.prototype.indexOf.call(document.getElementsByTagName('*'), element)