Dynamically load external javascript file, and wait for it to load - without using JQuery

后端 未结 3 2025
南旧
南旧 2020-12-01 03:14

I\'m trying to dynamically load an external .js file (according to an input I get from the user). Currently my code looks like this:

function createScript(sr         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 03:33

    If you have control over the source of the javascript that gets loaded, your best bet would be to have that code execute a pseudo-callback function that exists within your page context. This is something like the method used for JSONP. So, imagine on your calling page, you have this:

    function createScript(src, id) {
        if (document.getElementById(id) == null) {
            var newScript = document.createElement('script');
            newScript.setAttribute("type", "text/javascript");
            newScript.setAttribute("src", src);
            newScript.setAttribute("id", id);
            document.getElementsByTagName("head")[0].appendChild(newScript);
        }
    }
    
    function callbackFunc()
    {
      // make use of new functions here....
    }
    

    And each of your source files might end with this line:

    callbackFunc();
    

提交回复
热议问题