narusawa narusawa - 6 months ago 38
Javascript Question

jquery from google CDN is not defined

I am trying to inject jquery CDN by javascript. The following code, however, does not seem to work giving me an error: "$ is not defined". Any help will be appreciated!

var jqry = document.createElement('script')
jqry.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js')
jqry.setAttribute('type', 'text/javascript')
var jqui = document.createElement('script')
jqui.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js')
jqui.setAttribute('type', 'text/javascript')
document.head.appendChild(jqry)
document.head.appendChild(jqui)

if (typeof jQuery == 'undefined') {
alert('no jquery')
}

$... // codes using jquery

Answer

Scripts are being loaded asynchronously.

Listen onload event of the script element as script is not really loaded when if-condition is executed.

var jqry = document.createElement('script')
jqry.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js')
jqry.setAttribute('type', 'text/javascript');
document.head.appendChild(jqry)

jqry.onload = function() {
  if (typeof jQuery == 'undefined') {
    alert('no jquery')
  } else {
    alert('Loaded!');
    var jqui = document.createElement('script');
    jqui.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js')
    jqui.setAttribute('type', 'text/javascript');
    document.head.appendChild(jqui);
    jqui.onload = function() {
      alert('jquery-ui Loaded!');
    }
  }
}

A generalized function to load scripts asynchronously:

function loadScript(src, callback) {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = src;
  document.head.appendChild(script);
  script.onload = callback || function() {};
}
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js', function() {
  alert('jQuery Loaded!');
  loadScript('//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js')
})

Comments