Sequentially injecting and running jQuery in Chrome DevTools

Viewed 257

The following injects jQuery into Chrome Developer Tools.

jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
// ... give time for script to load, then type
jQuery.noConflict();

Though it works well, my goal is to sequentially run jQuery afterwards without having to separate the code.

I have tried:

setTimeout(function(){
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
}, 2000);
jQuery.noConflict();

Result: Uncaught ReferenceError: jQuery is not defined.

Running that a second time is successful.


That said, my next attempt was:

setTimeout(function(){
setTimeout(function(){
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
}, 1000);
jQuery.noConflict();
}, 2000);

Result: Uncaught ReferenceError: jQuery is not defined.

Running that a second time is successful.


What can I do to make the delay work?

1 Answers

Usually it's something like this:

const jq = document.createElement('script');
jq.onload = () => {
  jQuery.noConflict();
};
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";
document.head.appendChild(jq);

Set .onload (or however you want to set your load event handler) before setting .src as some browsers don't actually need script to be part of the document and will load as soon as .src is set.

Related