2

I need to Reload a specific js or css file by 2 second of interval. can it be done by jQuery?

I have tried to php_loop to execute this, but it is added the script one more time. Therefore I have tried to setinterval() but it didnt respond.

Kevin
  • 1,241
  • 7
  • 20
  • what do you mean *exactly* by reload the js or css ? what is the purpose ? because at the moment i don't see any case where you would need to really *reload* one of them. And can you provide what you tried with `setInterval` ? – Frankich Jul 08 '19 at 11:27
  • To be specific, I need to reload the google analytics code js to check something. – Kevin Jul 08 '19 at 11:31
  • Giving an arbitrary reason without further explanation, is not what I would call “specific”. _“I need to reload the google analytics code js to check something”_ - most such libraries have some sort of initialization code, and it is often explicitly build-in into those, that they do not do the same work twice, if the script file was _accidentally_ embedded twice - so that could perhaps already be the reason, why what you tried with setInterval “didn’t work”. So please try and _actually_ be specific now - explain why you need this, and _show_ what you have tried so far. Go read [ask], please. – misorude Jul 08 '19 at 11:38
  • to be specific means, I need to refresh the google analytics code to show the user count. – Kevin Jul 08 '19 at 12:27
  • Are you sure you want to reload the code and not only trigger an action based on the already loaded code? – Nico Haase Jul 08 '19 at 13:05
  • I didn't get you. please explain once. – Kevin Jul 08 '19 at 13:14

1 Answers1

3

Reloading JavaScript or CSS should not be done without reloading the page.

  • Reloading CSS would cause the Page to re render. (Not good if done every 2 seconds)
  • Reloading JavaScript would cause a lot of problems with bindings, ...

I don't know what you are doing, but I would consider the "There is an update: Please refresh the page" alert box approach. (Like Gmail does for example)

If you still want to reload specific JavaScript or CSS, you can set the src attribute of the script/style tags with another version number (file.js?v=randomnumber).

Look at this answer for example (You still need to add the version part, as said before, to fix caching issues):

function reload_js(src) {
    $('script[src="' + src + '"]').remove();
    $('<script>').attr('src', src).appendTo('head');
}
MauriceNino
  • 6,214
  • 1
  • 23
  • 60
  • Hi, thanks for your code. What if I need to reload the google analytics script only? because I need to show some user activity on a website. – Kevin Jul 08 '19 at 12:31
  • 1
    @Kevin I dont know much about the google analytics script, but I guess it has a source right? If yes, take the approach from my answer. If no, give it an ID and sub `src` for `id` in the code from my answer. – MauriceNino Jul 24 '19 at 10:26