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?
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.
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.
JavaScript reload() method In JavaScript, the reload() method is used to reload a webpage. It is similar to the refresh button of the browser.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With