javascript - How to dynamically add script which will be executed right now? -


there simple page:

<html>   <head>     <script type="text/javascript" src="scripts/x.js"></script>   </head>   <body>     <script type="text/javascript">       console.log($);     </script>   </body> </html> 

'scripts.x.js':

var script = document.createelement('script'); script.type = 'text/javascript'; script.src = 'https://code.jquery.com/jquery-1.12.3.min.js'; script.async = false; script.defer = false; document.currentscript.parentnode.insertbefore(script, document.currentscript.nextsibling); 

this script adds new external script tag right after current script, doesn't work, because 'console.log' writes error 'index.html:8 uncaught referenceerror: $ not defined'. doing wrong? in advance!

the problem because of asynchronous i/o model of javascript script doesn't expect. think script stop executing while jquery loading, continue once external script (https://code.jquery.com/jquery-1.12.3.min.js in case) loaded.

what happens i/o operation done thread , time js interpreter reaches console.log call, i/o hasn't finished yet , therefore $ hasn't been initialized yet.

i suggest try requirejs - handles loading of external scripts asynchronously.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -