Why is the tag tag removed in JavaScript Injection from the Google Chrome extension?

From Paste code into page context using content script

var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.extension.getURL('script.js');
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);

I read all the topics in Stack ... and the documentation from Google regarding the Google Chrome and script extensions, but I don't understand the purpose of line 5 in the above injection script code:

this.parentNode.removeChild(this); 

I may need some JavaScript training, I know, but what happens if you don't delete the script after executing it? Will the expansion crash? Is it just for pure coding or has a specific purpose?

+4
source share
3 answers

<script> :

- , script, script.parentNode.removeChild(script);. , . script , , <script> . - Rob W Aug 29 '13 13:35

, 2/3, . 1 script (<script src=...>), . node script, script , script . , node onload:

s.onload = function() {
    this.parentNode.removeChild(this);
};

, , .remove:

s.onload = s.remove;
+3

, , script , script. Chrome , , .

+1

, script:

  • <script>:

    var s = document.createElement('script');
    
  • ...

  • src URL- script script.js ( ) chrome.extension.getURL(), - "chrome-extension://abcdefghijklmnopqrstuvwxyz/script.js":

    s.src = chrome.extension.getURL('script.js');
    
  • onload script, , script :

    s.onload = function() { ...
    
  • : onload script , . , script , , , . this , script, :

    this.parentNode.removeChild(this);
    

    : " script ".

  • onload.

  • script . <head> , , <html>, :

    (document.head||document.documentElement).appendChild(s);
    

    : " <head>, script, <html>".

TL;DR; script , .

script?

, , , , .

  • , script , : , .

  • Secondly, deleting the code can be useful if the script is really large, because it can slow down the page loading time and Javadcript execution, and it can also slow down the process of "checking" because opening a large script tag using the Chrome dev tool window slows down the window itself and may even crash Chrome if it needs too much CPU.

0
source

Source: https://habr.com/ru/post/1540132/


All Articles