异步通过appendChild加载的Script最后加载问题及自定义脚本咨询
First, the Root Cause
When you use appendChild() to add a <script> element to the <head>, browsers treat this as an asynchronous load by default. That means the browser won't pause parsing the rest of the page to wait for this script to download—it keeps processing other resources (like sync-loaded scripts, stylesheets, images) that are already in its request queue.
If you're triggering this load after the page has finished parsing (e.g., inside a DOMContentLoaded listener), the script will naturally start loading only after all initial page resources are done, making it seem like it's always last. Even if you call it earlier, async scripts don't block the parser, so their execution order depends on when their download finishes relative to other resources.
Fixes to Try
1. Use async or defer Attributes (Choose Based on Your Needs)
These attributes give you control over how the browser handles the script's execution:
async: Use this if your script doesn't depend on other scripts or the DOM. The browser will execute it as soon as it finishes downloading, but execution order isn't guaranteed if you load multiple scripts this way.oScript.async = true;defer: Perfect if you need scripts to execute in the order they're added, and only after the DOM is fully parsed. It won't block page rendering either.oScript.defer = true;
2. Adjust the Insertion Position for Higher Priority
Instead of appending to the end of <head>, insert the script at the start of the <head>—this puts it earlier in the browser's request queue, so it gets prioritized:
const head = document.querySelector('head'); head.insertBefore(oScript, head.firstChild); // Insert at the top of <head>
3. Force Synchronous Loading (Not Recommended)
If you absolutely need the script to load and execute before anything else, you can disable async behavior. This will block page parsing until the script loads, which hurts performance—only use this if you have no other option:
oScript.async = false; oScript.src = script; document.head.appendChild(oScript);
4. Use Promises to Control Load Order
If you're loading multiple scripts and need them to run in a specific sequence, refactor your require method to return a Promise. This lets you chain loads and ensure order:
var Dim = (function(s){ var storage; function loadError(oError) { throw new URIError("The script " + oError.target.src + " is not accessible."); } return { require : function(script){ return new Promise((resolve, reject) => { const oScript = document.createElement("script"); oScript.type = "text/javascript"; oScript.onerror = reject; oScript.onload = resolve; oScript.src = script; document.head.appendChild(oScript); }); } }; }(window)); // Example: Load scriptA first, then scriptB Dim.require('scriptA.js') .then(() => Dim.require('scriptB.js')) .catch(err => console.error("Load failed:", err));
内容的提问来源于stack exchange,提问作者MMJM

