Search code examples
javascripthtmlfeedscript-tag

How to force a script reload and re-execute?


I have a page that is loading a script from a third party (news feed). The src url for the script is assigned dynamically on load up (per third party code).

<div id="div1287">
    <!-- dynamically-generated elements will go here. -->
</div>

<script id="script0348710783" type="javascript/text">
</script>

<script type="javascript/text">
    document.getElementById('script0348710783').src='http://oneBigHairyURL';
</script>

The script loaded from http://oneBigHairyURL then creates and loads elements with the various stuff from the news feed, with pretty formatting, etc. into div1287 (the Id "div1287" is passed in http://oneBigHairyURL so the script knows where to load the content).

The only problem is, it only loads it once. I'd like it to reload (and thus display new content) every n seconds.

So, I thought I'd try this:

<div id="div1287">
    <!-- dynamically-generated elements will go here. -->
</div>

<script id="script0348710783" type="javascript/text">
</script>

<script type="javascript/text">
    loadItUp=function() {
        alert('loading...');
        var divElement = document.getElementById('div1287');
        var scrElement = document.getElementById('script0348710783');

        divElement.innerHTML='';
        scrElement.innerHTML='';
        scrElement.src='';
        scrElement.src='http://oneBigHairyURL';
        setTimeout(loadItUp, 10000);
    };
    loadItUp();
</script>

I get the alert, the div clears, but no dynamically-generated HTML is reloaded to it.

Any idea what I'm doing wrong?


Solution

  • How about adding a new script tag to <head> with the script to (re)load? Something like below:

    <script>
       function load_js()
       {
          var head= document.getElementsByTagName('head')[0];
          var script= document.createElement('script');
          script.src= 'source_file.js';
          head.appendChild(script);
       }
       load_js();
    </script>
    

    The main point is inserting a new script tag -- you can remove the old one without consequence. You may need to add a timestamp to the query string if you have caching issues.