I’m creating a widget for people to use on their websites, however to keep the widget future-proof, i want it to be self constructing using an external javascript.
So the widget code i would ask people to put on their websites would be something like:
<div id="my_widget"></div>
<script type="text/javascript" src="http://www.external-domain.com/mywidget.js"></script>
mywidget.js would then use jquery’s .load() to populate the #my_widget div with an iframe.
Problem is this doesn’t work….
what do i need to do?
(note i dont want to have the iframe in the code i give to my customers)
It depends on what url you are specifying in the
loadfunction. If this url is not hosted on the same domain that executes the page containing this script won’t work due to same origin policy restriction. One possible workaround to make cross domain ajax calls is to use JSON-P if you have control over the server side script which is used in theloadfunction.Here’s the idea behind JSON-P:
Let’s suppose that
http://domainA.com/myscript?jsoncallback=fooreturns the following response:Now inside
mywidget.jsyou could call this script:All that is left is to tell the users include
mywidget.jsscript and provide a placeholder withid="my_widget"to host the results (you could even generate this placeholder in the success callback).Remark: When using JSONP you are limited to GET requests only. This means that there’s a limit in the size of the request you can send.