Amit Malviya
Amit Malviya

Reputation: 11

How to use Web worker with AJAX

Is there is any way to call ajax function in web worker.Actually i am directly using ajax function to get the response but data is too much heavy,due to that my window is going to be freeze until the response will come.To overcome this problem now i am using web worker.The data(JSON) is dynamic.So can you please tell me how to call ajax function so that i can use it in my application.Here i am attaching web-worker code.

//Worker.js File

var myCallback = function(data){
    self.postMessage(JSON.stringify(data));
};

self.addEventListener('message', function(e) {
    importScripts('json.js?callback=myCallback');
}, false);

//JOSN.js File

function getResult(){
     var randomNum = (Math.floor(Math.random() * 5) + 1),
     cacheBuster = (Math.floor(Math.random() * 10000) + 1);
    $.ajax({url:'http://examples.kevinchisholm.com/utils/json/jsonp.php?callback=myCallback&cacheBuster=' + cacheBuster + '&sleep=' + randomNum,
        type:'POST',cache:false,data:datas,dataType:"json",async:false,
        success:function(xmlResponse){ 
        return xmlResponse;
    }});    
}

getResult();

Upvotes: 0

Views: 727

Answers (1)

Tirthesh Jain
Tirthesh Jain

Reputation: 13

Yes you can definitely use ajax in web worker by simply using XML Http Request or fetch API and can post the message using postmessage by using my code hope it helps:->

#Declaring Worker

var worker= new Worker("ajax123.js");
worker.onmessage=function(data){                                        
    document.body.innerHTML=data.data;                                
}
 

#Web Worker Code

fetch(filename)
    .then(response => { return response.text(); })
    .then(data => { self.postMessage(data) });

Upvotes: 1

Related Questions