问题:
I am experimenting with Classes available in javascript and have setup a simple test case as follows:
<script src="myclass.js></script>
<script>
va...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I am experimenting with Classes available in javascript and have setup a simple test case as follows:
<script src="myclass.js></script>
<script>
var test = new MyClass();
</script>
myclass.js contains the following:
class MyClass {
constructor() {
}
}
This works as expected.
However, if I dynamically load "myclass.js" using jQuery.getScript() function the browser returns the following error:
Uncaught ReferenceError: MyClass is not defined
Things I have double checked are:
The code to instantiate the class is placed within the success callback of the getScript function
And also that the script is actually being loaded and executed (with a simple console log)
However I seem to have a brick wall with this. Is there any reason why a class cannot be instantiated from if the file containing the class is loaded from a javascript file using the jQuery.getScript function?
This is the code which does not work:
<script>
$(document).ready(function() {
$.getScript('myclass.js', function () {
var test = new MyClass();
});
});
</script>
Testing on Chrome Version 71.0.3578.98 (64-bit)
回答1:
Have a look at this question and its answers as well as the documentation such says the success callback is run after loading but not necessarily after executing the script.
To sum up, it might suffice to run your code by appending a then
(or done
) handler:
$.getScript(url).then(function() {
var test = new MyClass();
});
If this is not enough you should fall back to use a setInterval
-triggered check for the existence of the class (stop the interval after finding the class). This way you are avoiding any dependency on the specific browser behavior when the script gets executed after loading it.
function afterScriptExecuted() {
var test = new MyClass();
}
function testScriptExecuted() {
return window.MyClass !== undefined;
}
$.getScript(url).then(function() {
var id = setInterval(function() {
if (testScriptExecuted()) {
clearInterval(id);
afterScriptExecuted();
}
}, 50);
});
回答2:
In the end, only the following approach worked for me (rather than using jQuery.getScript)
var script = document.createElement('script');
script.onload = function () {
var test = new MyClass();
};
script.src = '/myclass.js';
document.head.appendChild(script);