Cannot instantiate a class when script is injected into document dynamically

问题: 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); 
  • 发表于 2019-01-01 20:12
  • 阅读 ( 192 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除