“This is the 27th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge in 2021”

DOM programming

Dynamic script

The script tag is used to insert JS code into the HTML. There are two ways:

  1. Directly in thescriptWrite JS code in the tag block
  2. throughscriptIn thesrcProperty to introduce an external JS script file
Introducing third-party JS

Now, we need to append third-party JS to the DOM. Using jquery as an example, we can create a new script node with the following JS and append it to the head:

let script = document.createElement("script");  / / 1.
script.src = "https://code.jquery.com/jquery-3.1.1.min.js";  / / 2.
document.head.appendChild(script);  / / 3.
Copy the code

Note that the newly defined script node has not yet been added to the DOM and parsed, so it will not download the corresponding external file from SRC


Now, let’s talk about the DocumentFragment tag mentioned in the previous article, which allows multiple node changes to be aggregated to virtual nodes outside the DOM and then synchronized to the DOM again

As shown in the figure, when the Script tag is added to the DocumentFragment, it will not trigger the loading of external resources. Only when the change operation is synchronized to the DOM and the DOM is re-rendered, the external resources will be loaded

Add JS code snippets

As mentioned in a previous article, for most elements in HTML, there are Text child nodes. We can define a script node and add the JS fragment to the DOM as the Text value of the Text node, the child node of the script

Dynamic style

CSS can also be loaded in two ways:

  1. throughlinkOf the labelhrefProperty loads the external stylesheet
  2. throughstyleThe tag inserts internal styles into the HTML
Introducing third-party CSS

By creating a link tag and setting the necessary attributes and then adding them to the head tag, a link tag and a style tag are parsed only under the head tag. Where script tags are added to the DOM only affects the order in which js code is parsed

let link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = "styles.css";
document.head.appendChild(link);
Copy the code
Insert CSS fragments for HTML

In the same way as inserting a JS snippet, the CSS style to be inserted is inserted as the value of the text child node of the style tag

let style = document.createElement("style");
style.type = "text/css";
style.appendChild(document.createTextNode("body{background-color:red}"));
document.head.appendChild(style);
Copy the code

The CSS styles added in the above manner are immediately rendered and used by the DOM