Javascript including files to another javascript fails after loaded by document.appendChild() Code (markup): and gives undefined function error. I loaded javascript files to another javascript file and tried to run loaded function and failed. What is the problem loading javascript files by dynamically. The reference said that it might be depend on the browser to function. http://unixpapa.com/js/dyna.html - "JavaScript Madness: Dynamic Script Loading" This is what exactly I did; var head= document.getElementsByTagName('head')[0]; var script= document.createElement('script'); script.type= 'text/javascript'; script.src= 'file.js'; head.appendChild(script); Code (markup): And after run the function loaded, returned undefined errors even the script is loaded and added at the chrome console. It means that the files are loaded but do not function well, by objects or methods not specified well. Tell me what is the best way to load javascripts to another javascript file without undefined errors. Or tell me how to make them call the function without errors by dynamic loading. john3825
Looks okay for me, for that small part You get undefined error because file.js script has failed to find its own target element? That this element itself was still being built, maybe? Hendra
-And after run the function loaded, returned undefined errors even the script is loaded and added at the chrome console. It means that the files are loaded but do not function well, by objects or methods not specified well. The problem is; Dynamic loading too much depending on the browser, so the gives errors. Is there any other way that to locate the function on the other script so that the do not give undefined errors. I tried $.getScript() and DOM elelement like above.
Test that theory by placing a simple echo js file, if that works, the issue must be with the file. If it doesn't work, then your theory is correct.
Your issue is because the browser will load the imported script asynchronously. So any code depending on that imported file does not function because they are not in order. If you not actually trying to include the base jquery framework, i personally would use this approach. Place the jquery framework static, and then use a jquery function to load a script which may hold all your function to execute <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $.getScript('/path_to_script.js', function() { // script is loaded // call some functions from it here }); </script> HTML: