How to postpone JavaScript parsing For 2 scripts on a page, Jquery is loaded first and its plugin the second. I tried to do so

<script type='text/javascript'> (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.defer= true; ga.src = "http://site.ru/js/plagin.js" var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> 

but console error Uncaught ReferenceError: $ is not defined - plagin.js

  • What would you like ? :) fewer clever words :) see answer: - zb '14
  • @eicto: the answer fell off on the way? :) - VladD
  • @Vlad buttons pressed for a long time :) on the spot answer - zb '14
  • @eicto: then +1 - VladD

1 answer 1

just load the second script after the first ( onload );

 var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"; document.head.appendChild(ga); ga.onload = function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.defer = true; ga.src = "http://site.ru/js/plagin.js"; ga.onload = all_other; document.head.appendChild(ga); }; document.head.appendChild(ga); function all_other() { $(function () { console.log('Hello jquery and plugin loaded, document ready!'); }); }