Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to refresh just the javascript include while doing development?

Tags:

javascript

While doing development on a .js file I'd like to just refresh that file instead of the entire page to save time. Anyone know of any techniques for this?

like image 735
sbuck Avatar asked Mar 12 '11 19:03

sbuck


People also ask

How do you refresh JavaScript?

You can use the location. reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button. The reload() method is the main method responsible for page reloading.

How do I refresh only part of a page in HTML?

Use Ajax for this. Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one. e.g.

Which method is used to refresh the webpage in JavaScript?

JavaScript reload() method In JavaScript, the reload() method is used to reload a webpage. It is similar to the refresh button of the browser.

How do I refresh a page after some time?

Using history.go(0) Method: This method loads a URL from the browser's history depending on the parameter passed to it. If the parameter passed is '0', it reloads the current page. The refresh code can be executed after a certain period of time using the setTimeout() function.


1 Answers

Here is a function to create a new script element. It appends an incremented integer to make the URL of the script unique (as Kon suggested) in order to force a download.

var index = 0;
function refreshScript (src) {
  var scriptElement = document.createElement('script');
  scriptElement.type = 'text/javascript';
  scriptElement.src = src + '?' + index++;
  document.getElementsByTagName('head')[0].appendChild(scriptElement);
}

Then in the Firebug console, you can call it as:

refreshScript('my_script.js');

You'll need to make sure that the index itself is not part of the script being reloaded!

The Firebug Net panel will help you see whether the script is being downloaded. The response status should be "200 OK" and not "304 Not Modified. Also, you should see the index appended in the query string.

The Firebug HTML panel will help you see whether the script element was appended to the head element.

UPDATE:

Here is a version that uses a timestamp instead of an index variable. As @davyM suggests, it is a more flexible approach:

function refreshScript (src) {
  var scriptElement = document.createElement('script');
  scriptElement.type = 'text/javascript';
  scriptElement.src = src + '?' + (new Date).getTime();
  document.getElementsByTagName('head')[0].appendChild(scriptElement);
}

Alexei's points are also well-stated.

like image 171
inkfist Avatar answered Sep 19 '22 08:09

inkfist