简体   繁体   中英

Load jQuery in snippet and add elements to blank page

Disclaimer. I am fairly new to JavaScript so if my workflow does not make sense at all or my vocabulary is yet not precise enough, please advise me of how I should do it differently.

Current Approach

I want to learn more about Javascript and external libraries. Thus, I created a snippet under the DevTools sources panel in Chrome, opened about:blank and executed the following code (which I copied and paste from different sources):

Code

(function(head) {
  var newscript = document.createElement('script');
  newscript.type = 'text/javascript';
  newscript.async = true;
  newscript.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js";
  (document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript);
})(document.getElementsByTagName('head'));

function jQueryReady() {
  if (window.jQuery) {
    jQuery.noConflict();
    my_code(jQuery);
  } else {
    setTimeout(jQueryReady, 100);
  }
}

jQueryReady();

function my_code($) {
  console.log("OK");
  $('head').append($('script', {
    type : 'text/javascript',
    async: true,
    src  : 'https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.js'
  }));
  $('head').append($('link', {
    rel : 'stylesheet',
    href: 'https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.css'
  }));
}

Results

When I then look at the source code of about:blank , I see that the jQuery script is correctly inserted into the head, I see that the console shows OK , but neither the spectrum JavaScript nor the CSS is inserted into the head.

Questions

  1. Why is the code not added to the HTML file? What do I need to change to make it work?
  2. If I run teh code from my_code directly in teh console everything seems to work fine? Why?
  3. What is a proper way of playing around with JavaScript without writing an own html file? Does the approach via snippet and about:blank make sense? I need to reload about:blank whenever I make changes to the snippet, so I guess there is a more elegant way to do so. Any tipps on how to do that better?
  1. I believe it is because in jQuery, when you want to create new elements, it is necessary to wrap tag name in "<>" signs like this:

$('head').append($('<script>', { type: 'text/javascript', async: true, src: ' https://cdnjs.cloudflare.com/ajax/libs/spectrum/1.8.0/spectrum.js ' }));

  1. In my opinion it is good idea to try sites like jsfiddle.net or codepen.io, where at least you can add libraries like jQuery easier without writing additional importing scripts and it is easier to maintain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM