Why is it different when dynamically creating script and dynamically creating img assigning src.

in the process of dynamically creating script and img, why can img request resources immediately after assigning src, while script must be added to the page to load resources

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript">
        
        window.onload = function(){
            var img = new Image();
            img.src = "./function.JPG";
            img.onload = function(){
                console.log("");
            }

            setTimeout(function(){
                console.log("10");
                document.getElementsByTagName("body")[0].appendChild(img);
            },10000)
            /*
                
                10   --->10s
            */

            //createElement
            var img2 = document.createElement("img");
            img2.src = "./function.JPG";
            img2.onload = function(){
                console.log("");
            }

            setTimeout(function(){
                console.log("10");
                document.getElementsByTagName("body")[0].appendChild(img);
            },10000)
            /*
                
                10   --->10s
            */


            var script = document.createElement("script");
            script.src = "./zepto.js";
            script.onload = function(){
                console.log("script");
            }
            setTimeout(function(){
                console.log("10");
                document.getElementsByTagName("body")[0].appendChild(script);
            },10000)
            /*
                10   --->10s
                script
            */
        }
    </script>
</body>
</html>

both assign values to dynamically created script and img, so why can img request directly, and script can only be requested when it is added to the page? And the second test shows that it has nothing to do with document.createElement.

Mar.23,2021

my understanding is that the picture itself is an element, and when you directly access the address of the picture, you can display the picture without relying on the page.
but js is different. Js must rely on an execution environment such as a browser page before it can be executed. Your browser accesses a js, directly and only gets a bunch of strings.

img and script themselves are different. That's why browsers have this feature: img can request directly, and script will not be requested until it is added to the page.

my own understanding is not necessarily correct.


this is handled by the browser or the specification requires that
img can be loaded directly. Another reason is that it is convenient to preload processing to enhance the experience, while js does not need such processing, and often the implementation of js will affect the html display, so it is more appropriate to enter the html location before actually loading.

Menu