Coffeehouse
Coffeehouse

Reputation: 505

Changing jQuery .load into native Javascript

I need to run a local project without Inet connection and therefore would like to be able to include jQuery into the local folder, which should be no problem. But it is.

The available space is extremely limited and the cpu power is a joke (it is a small control unit for an industrial machine), even the 60kB js framework slows it down a lot.

That is why I would like to include the following as native Javascript:

window.onload = function () {
    var auto_refresh = setInterval(
        function () {
            $('#w1').load('testing.html #w1');
        }, 1000);
};

I read that AJAX without jQuery is a whole lot more complicated. Can anyone help?

Upvotes: 1

Views: 706

Answers (3)

Vivek
Vivek

Reputation: 4886

First I would advice you to use DOM Ready event instead of .load. Something like this:

if(document.addEventListener)
    document.addEventListener('DOMContentLoaded', init());
else
    document.attachEvent('onreadystatechange', function(){
        if(document.readyState == 'complete') init();
});

function init(){//do something}

And for AJAX you can write something like this:

var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        // do something on ajax success
    }
}    
xmlhttp.open("GET","info.php",true);
xmlhttp.send();`

Upvotes: 0

Vlad Nikitin
Vlad Nikitin

Reputation: 1951

to implement ajax calls cross browser you will need something like this sendRequest function https://stackoverflow.com/a/2557268/2842568

Upvotes: 0

Alberto Zaccagni
Alberto Zaccagni

Reputation: 31560

If you need just a functionality out of a bigger library I suggest you to have a look at http://microjs.com, if you search for "ajax" you will get this at the top of the results https://github.com/ForbesLindesay/ajax

I haven't used this myself but it seems quite straightforward (and it just weights 2kb):

ajax.getJSON("sample.json", function (res) {
  document.getElementById('result').innerHTML = '"' + res.foo + '"';
});

If 2kb or using such a library is not what you want have a look at this question on Stackoverflow: How to make an AJAX call without jQuery?

Upvotes: 1

Related Questions