0

i made a script to import jquery into a website but for some reason it doesnt work. this is it

function loadJQuery() {
  let jquery = document.createElement('script');
  let script = document.createElement('script');
  jquery.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js';
  jquery.type = 'text/javascript';
  script.innerHTML = `
  //insert jQuery here
  `;
  document.head.appendChild(script);
  document.head.appendChild(jquery);
}
loadJQuery();

like in this case when you pres the spacebar it should alert a happy greeting but it just says that $ id not defined. am i dumb or something

function loadJQuery() {
  let jquery = document.createElement('script');
  let script = document.createElement('script');
  jquery.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js';
  jquery.type = 'text/javascript';
  script.innerHTML = `
  $(document).keydown( function(event) {
    if (event.which == 32) {
      alert('hi!ツ');
    }
  });
  `;
  document.head.appendChild(jquery);
  document.head.appendChild(script);
}
loadJQuery();
joeCEB
  • 83
  • 8
  • Go have a good read of https://stackoverflow.com/questions/8996852/load-and-execute-order-of-scripts – CBroe Nov 18 '21 at 14:47

1 Answers1

0

you can use import

function loadJQuery() {
import('https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js').then(()=>{
    $(document).keydown( function(event) {
        if (event.which == 32) {
            alert('hi!ツ');
        }
    });
})
}
loadJQuery();
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Sebastian
  • 315
  • 1
  • 10