My current project involves making a cross domain request using the script tag hack and jsonp. In the callback function, I am attempting to write the received data to the DOM using document.write()
.
Although I am aware that it is recommended to use appendChild/innerHTML instead of doc.write()
, I am facing a constraint where I do not have a class/id hook to the element I need to write to. As a result, my only option is to utilize document.write()
to write "in place".
The following code snippet can be found within an HTML div enclosed 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
*/
Despite experimenting with document.write
including a static string inside the callback function, the function seems to be ineffective. I initially believed that invoking document.write
before the onload
event would successfully insert text onto the page based on information from JavaScript and HTML Script Tags
What could be causing the issue with document.write()
not being able to write to the DOM? Furthermore, are there alternative methods or better approaches to achieving this task?