Load a JavaScript file dynamically and call a function from it

This is how you provide an embed code, which will load a JavaScript file dynamically into the website and call a function from inside the file with externally passed params.

<script>
    (function () {
        var params = {}; // If you want to pass anything, to the called function
        var script = document.createElement("script");
        script.type = "text/javascript";
        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    theFunctionInsideExternalScript(params);
                }
            }
        } else {
            script.onload = function () {
                theFunctionInsideExternalScript(params);
            }
        }
        script.src = "your-external-script-file.js";
        document.getElementsByTagName("head")[0].appendChild(script)
    })();
</script>

4 Comments

  • Misha |

    Thank you for this example. What I can’t figure out from this is: when will a readyState exist for the script , and when won’t it?

  • Jsx |

    Hello, script.readyState was a non-standard implementation present in some older browsers. So that if-condition is only applicable for older browsers. script.readyState will never exist when run in modern browsers. script.onload is the standard and modern way to know when scripts are loaded.