ta32
ta32

Reputation: 148

import third-party library from cdn using inline JavaScript

I am trying to import the interactjs library from a cdn. It works if you add a script tag from the head. However I want to be able to load this library using JavaScript and bring it to scope.

example in the following codepen: https://codepen.io/ta32/pen/abLgyGW?editors=1111

  script.type = "text/javascript";
  script.src = "https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js";
  document.head.appendChild(script);
  eval(script);

non of the techniques mentioned in the articled worked https://levelup.gitconnected.com/how-to-load-external-javascript-files-from-the-browser-console-8eb97f7db778

Is it an issue with this particular library?

I also tried importing it from the chrome console and it didn't work either. I think there should be a way to load third-party libraries and bring them into scope without having to add script tags in the head.

Upvotes: 3

Views: 1909

Answers (1)

tao
tao

Reputation: 90068

When you add a <script> tag to DOM, it doesn't load instantly. And the browser doesn't halt current script's execution until the tag has been loaded and its contents evaluated/run.

To delay execution of the next lines of code until after the script has loaded, place them inside a function and specify that function's name as the script's onload attribute.

See it working:

const myFunc = () => {
  const position = {
    x: 0,
    y: 0
  };
  interact('.draggable').draggable({
    listeners: {
      start(event) {
        console.log(event.type, event.target)
      },
      move(event) {
        position.x += event.dx
        position.y += event.dy
        event.target.style.transform =
          `translate(${position.x}px, ${position.y}px)`
      },
    }
  })
};

const script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js';
script.onload = myFunc;
document.head.appendChild(script);
.draggable {
  width: 25%;
  min-height: 6.5em;
  margin: 1rem 0 0 1rem;
  background-color: #29e;
  color: white;
  border-radius: 0.75em;
  padding: 4%;
  touch-action: none;
  user-select: none;
}
<div class="draggable"> Draggable Element </div>

Upvotes: 4

Related Questions