Closed
Description
Description
jQuery .load
function errors if loading html with auto-removing script tag. Callback function is not executed.
While this is kind of a non-issue as jQuery removes scripts with the .load
function anyways and can be fixed just by removing the document.currentScript.remove();
from the loaded file, it sort of breaks stuff when I need that file to be loaded elsewhere via different methods and do require the script removal.
Link to test case
Not sure how to demonstrate the .load
function with the links provided as I need more than 1 file to show the error. So, here's the two html files needed to reproduce the issue.
File: test.html
<!DOCTYPE html>
<html>
<body>
<span id="light_dark_msg">
<script>
if (window.matchMedia && window.matchMedia("(prefers-color-scheme: light)").matches) {
$("#light_dark_msg").html(
"<b>P.S.</b> Have you tried viewing this site with your browser in dark mode?"
);
} else {
$("#light_dark_msg").html(
"<b>P.S.</b> Have you tried viewing this site with your browser in light mode?"
);
}
document.currentScript.remove(); // This causes jQuery to error if attempting to load this page as the script is already gone by the time the jQuery script remover gets to it.
</script>
</span>
</body>
</html>
File: test2.html
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script>
$(document).ready(() => {
$("#main").load("test.html", function () {
// Function errors out. Callback function not executed.
this.dispatchEvent(new Event("loading_complete"));
});
});
</script>
</head>
<body>
<div id="main"></div>
</body>
</html>
Error message:
Uncaught TypeError: Cannot read properties of null (reading 'removeChild')
at DOMEval (jquery-3.7.1.js:130:44)
at domManip (jquery-3.7.1.js:5951:8)
at jQuery.fn.init.append (jquery-3.7.1.js:6088:10)
at jQuery.fn.init.<anonymous> (jquery-3.7.1.js:6182:18)
at access (jquery-3.7.1.js:3905:8)
at jQuery.fn.init.html (jquery-3.7.1.js:6149:10)
at Object.<anonymous> (jquery-3.7.1.js:10229:9)
at fire (jquery-3.7.1.js:3223:31)
at Object.fireWith [as resolveWith] (jquery-3.7.1.js:3353:7)
at done (jquery-3.7.1.js:9627:14)