-1

I have a script in my html file as this

              <script>
            if (window.TamaraProductWidget) {
      
              window.TamaraProductWidget.render();
            }
          </script>

I did this in my ts class to import the script src

      this.myScriptElement = document.createElement("script");
  this.myScriptElement.src = "https://.....-widget.min.js";
  document.body.appendChild(this.myScriptElement);

How do I call it in my typescript class? Since it's not working, but if I call window.TamaraProductWidget.render(); in console of browser it works well.

5
  • 1
    How did you import the script file? You need it above your <script> tag. Commented Aug 11, 2022 at 13:44
  • 1
    You need ambient declarations so TypeScript knows the shape of TamaraProductWidget and that it's available in the global object Commented Aug 11, 2022 at 13:50
  • Make sure to import that widget script before that inline script is run. Commented Aug 11, 2022 at 13:53
  • What do you mean by "it's not working"? That's a sentence you should avoid, we know you're here because something is not working. Instead, explain how it isn't working. Do you have a TypeScript error? A runtime error? Commented Aug 11, 2022 at 13:56
  • Whoever closed this question as a dupe should be more careful. The question is about TypeScript, now about how to load a script dynamically. Notice they are able to call window.TamaraProductWidget.render(); from the console without a problem. Commented Aug 11, 2022 at 14:23

1 Answer 1

2

It does not look like TamaraProductWidget provides TypeScript definitions. The best you can do is tell TypeScript that it's available globally as any.

// This does not create a var statement, 
// it just tells TS that the object is available globally
declare var TamaraProductWidget: any;
// No TypeScript errors
window.TamaraProductWidget.render();

See example on the TypeScript Playground

I recommend you ask the TamaraProductWidget team to provide TS definitions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.