Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify src of all script in a html page before the page is loaded

Is it possible to rewrite all src of all script tags in a html page before the js scripts are loaded using javascript?

I tried to use <plaintext> tag but I was wondering if there is a better solution.

like image 307
Giuseppe Pes Avatar asked Sep 20 '25 22:09

Giuseppe Pes


1 Answers

I think I made a working example of what you want. It uses MutationObserver to listen for node changes to body and changes the src of all scripts when found. It demands that your JavaScript is executed before the targeted files.

<script>
  // select the target node
  var target = document.body;

  // create an observer instance
  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      console.log(mutation.type)
      Array.from(document.querySelectorAll('script')).forEach(s => {
        if (s.src && s.src.indexOf('jquery') !== -1) {
          s.src = "" // this resets the script src
        }
      });

      console.log('Jquery is loaded:', typeof $ !== 'undefined')
    });
  });

  // configuration of the observer:
  var config = {
    childList: true
  };

  // pass in the target node, as well as the observer options
  observer.observe(target, config);
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js?hej"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js?oj"></script>
like image 90
E. Sundin Avatar answered Sep 22 '25 11:09

E. Sundin