Synchronous Script Injection Using document.createElement("script")
When attempting to call a .js file synchronously and use its functions immediately, there are limitations. The code snippet provided shows an attempt to load a script and call a function, but it fails because the script has not yet loaded.
While assigning a load event handler to the script may resolve the issue in some cases, it is not guaranteed to work consistently, especially if the included script injects additional scripts with their own functions.
To address this challenge, one approach involves creating a custom Include() function:
Include('my1.js'); Include('my2.js'); myFunc1('blarg'); myFunc2('bleet');
This function could use XMLHttpRequest to fetch the script and then evaluate it globally. An alternative is to create a script element, append it to the head element, and evaluate its source directly using eval(). However, this approach may be prone to scope issues.
Another option is to leverage existing script loading tools like Requirejs or yepnope, which handle the complexities of asynchronous script loading and provide robust solutions for various situations. By using these tools, developers can simplify the process of including and using external scripts.
The above is the detailed content of How to Call `.js` File Functions Synchronously?. For more information, please follow other related articles on the PHP Chinese website!