jquery script request not caching

2019-09-05 14:45发布

问题:

I am trying to cache a very simple javascript response. I am using rails and my views/projects/index.js.erb contains only the following:

          alert('hi');

and when I request

  $.ajax({
    type: 'GET',
    cache: true,
    url : '/projects',
    dataType: 'script'
  });

I get the popup 'hi' and I see in my server log that a request to Projects#index action as js has been made to it.

Then without refreshing the browser and I do it again

  $.ajax({
    type: 'GET',
    cache: true,
    url : '/projects',
    dataType: 'script'
  });

I see that the server still gets a request can anyone spot anything that I might have missed?

Thank you!

回答1:

I found out what's wrong. jQuery actually surround the incoming script with a so that the browser evaluates the incoming code. But the caching mechansim merely saves the code as text and when one re-request, it returns the code as text but not evaluate it. Therefore, one needs to eval the code explicitly