Can I avoid using global callback function when loading JSON-P?

I want to load my Google Calendar feed on my web page using JSON-P. To make the main content on the page load quicker, I inject the script tag for JSON-P into the head tag only after page is loaded. Google Calendar API returns a script with callback function, see example here.

Is it possible to avoid using global function as a callback function? I would like to wrap all the necessary code for injecting the tag and parsing the results inside one wrapper function.



No. When you are using JSON-P calls, the server returns something like below:


After you use <script> element to reference this JSON-P call URL, browser will download the JavaScript code and execute it, which means to execute your callback function using server-provided data.

If you don't want callback function to pollute your global namespace, just add some namespace to your callback function, like com.mycode.callback.

The biggest advantage of using JSON-P is that it can work around Same Origin Policy in browser and you can easily use data from other domains.


What you can do is using a method of the global where you application lives.



Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.