On my site I have a jquery function which retrieves data from another (secured) server as soon as the page is loaded. Using a jsonp call I currently load this data after document ready event:
<script type="text/javascript">
$(document).ready(function () {
$.getJSON(_secureHost + '/base/members/current.aspx?callback=?', function (data) {
initPage(data);
});
});
</script>
What I don't like about the above call, is that the jsonp can actually be exectued before the document ready event, thereby slowing down the page load. So if I include jquery inside the page (i.e. not referencing using the script tag), then the following code works great and the page loads faster:
<script type="text/javascript">
$.getJSON(_secureHost + '/base/members/current.aspx?callback=?', function (data) {
$(document).ready(function () {
initPage(data);
});
});
</script>
But including jquery in every page is a 23k overhead which I'd like to avoid. How can I test to see if jquery has been loaded and only the excecute the initPage() function when jquery has been loaded?
Edit: To be more precise I need check repeatedly if jquery is loaded and then exectue the event. A timer job could be the solution..
Solution: I've created a preinit which does the jquery check. My page loading couldn't be faster:). Thanks everyone!
function preInit()
{
// wait until jquery is loeaded
if (!(typeof jQuery === 'function')) {
window.setTimeout(function () {
//console.log(count++);
preInit();
}, 10); // Try again every 10 ms..
return;
}
$.getJSON(_secureHost + '/base/members/current.aspx?callback=?',
function (data) {
$(document).ready(function () {
initPage(data);
});
});
}