Scenario
A page invokes a remote script available at this url: http://url.to.script/myScript?ScriptParamsList. Let’s assume that:
- Async execution is not required.
- Displaying output is not required.
-
The script is called on a button click event. Let Handler() be the javascript event handler:
function Handler()
{
//invoke the remote script
}
Several methods are available to implement Handler() function:
- script vs img tag:
document.write('<script src="http://url.to.script/myScript?ScriptParamsList" type="text/javascript"></script>');
document.write('<img src="http://url.to.script/myScript?ScriptParamsList" />');
- jQuery .html() vs .load():
$('#TargetDiv').html('<img src="http://url.to.script/myScript?ScriptParamsList" />');
$('#TargetDiv').load('http://url.to.script/myScript?ScriptParamsList');
Question
Which are the advantages and the disadvantages?
document.writewill replace your current document when it’s called after the document is loaded. Never use this method.<script>allows you to fetch a request from an external domain, without being hindered by the same origin policy. Additionally, in the server’s response, you can add and execute JavaScript, which might be useful.Using
.html('<img ...>')makes no sense, unless your server returns an image with meaningful data. If you intend to only trigger a server request, the following would be better:$('..').loadis not going to work if the URL is located at a different domain, because of the same origin policy.I vote for the
new Image().src = '..';method. If you dislike this syntax, and want more jQuery, use:Note: The result may be cached. If you don’t want this to happen, append a random query string, to break the cache (eg.
url = url + '&_t=' + new Date().getTime()).