Looks like I found a solution to the problem. I would not suggest it, but this is the only way to load an external script from another before the DOMContentLoaded event DOMContentLoaded .
Decision
Since your main.js script is located in the <head> your document, you can be sure that it will be loaded and executed before any next part of the DOM. Given this, you can use the synchronous XMLHttpRequest to load the script and execute it .
This technique has its pros and cons:
Pros: you can load and execute any script up to DOMContentLoaded , as well as several scripts in sequence.
Cons: Your document will be frozen until the requests are completed.
Not so bad if your script is not huge, it will not affect the load time. We can still do it.
Implementation
First of all, make sure your custom.js script is served by a link that will always be available so that your request will not fail. Also make sure your main.js script does not have async or defer , so it will always be executed in <head> before the DOMContentLoaded event.
<script src="main.js" defer></script> <script src="main.js" async></script> <script src="main.js"></script>
Now that you are ready, in the main.js script you need:
Create and initialize a synchronous XMLHttpRequest object and send() a GET request for your content.js script.
Create a <script> element and put in it the result of your request (which is stored in the .responseText property of the request object).
Add a script to <head> to run it before loading the DOM.
In addition, if you also want your script to be deleted immediately after execution (therefore, it will not be displayed to users), you can:
- Remove the
<script> from the document after running its code. To do this, you need to listen to the onload .
In addition, if you want your code to run completely anonymously, you can wrap it inside an anonymous function to prevent access to it from the global scope.
Here is a brief example of what you need to do in your main.js file:
(function() { // Create the request and the script var xhr = new XMLHttpRequest(), s = document.createElement('script'); // Send the request to retrieve custom.js xhr.open('GET', 'path/to/custom.js', false); xhr.send(); // Listen for onload, and remove the script after execution s.addEventListener("load", function(e) { s.parentElement.removeChild(s); }); // Load the code inside the script and run it in the head s.textContent = xhr.responseText; document.head.appendChild(s); })();
Now your custom.js script will (anonymously) work until DOMContentLoaded , completing the mission!