Executing the function from the js file that has been included

Presented are two JavaScript files:

example.js

  let script = document.createElement('script');
    script.src = 'myfile.js';
    document.head.appendChild(script);
  myFunction();

myfile.js

 function myFunction() {
      alert("Hi there");
 }

Upon attempting to execute example.js, the error message "myFunction() is not defined" is encountered. I am seeking an explanation for this issue. Thank you in advance.

Answer №1

Simply including a script in the DOM does not guarantee that it has loaded, just like adding an image to the DOM doesn't mean the image is fully loaded. Loading scripts, images, or any URL content happens asynchronously, and the DOM does not wait for them to finish loading before continuing execution. In your code, you are calling a function immediately after adding the script to the page structure, but the script may not have finished loading yet.

Pure JavaScript solution:

Dynamically load external JavaScript file and wait for it to load without using jQuery

jQuery solution:

jQuery provides a helpful method called getScript:

$.getScript( "myfile.js", function( data, textStatus, jqxhr ) {
  // Once the script is loaded, functions can be called here
});

It's important to note that the appendChild method adds a child element as the last child. Considering your example:

<head>
<!-- other head elements -->
<script src="example.js"></script>
<!-- other head elements -->

<!-- FILE WILL BE ADDED HERE AS THE LAST CHILD -->
<script src="myFile.js"></script>
</head>

So, myFile.js will be added last in the head section, ensuring that it is not available in scripts added before it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the initial value of the input element following a modification

Is there a way to retrieve the original default value of an input field after changing it using .val()? In my HTML, I have various text-inputs with classes .large and .medium, each with its own default text value. What I'm trying to achieve is when a ...

Limit the allowable React Component prop type in Typescript

To promote composition within our codebase, we utilize passing components as props. Is there a way to enforce type checking for the components passed as props? For instance, let's consider a commonly used Typography component throughout the codebase, ...

Using jQuery to assign the value of a selected list item to an input field

I'm struggling with implementing a jQuery function to achieve the following: When a list item is clicked, it should add a 'select' class and remove any other selected list items The selected list item's data value should be set as ...

Using an AJAX function to retrieve data from two different server-side scripts and populate two separate HTML elements on the page

My goal in this coding situation is to change values in multiple DOM targets. The example from Tizag shows the DOM being altered within the onreadystatechange function, like this: if(ajaxRequest.readyState == 4){ document.myForm.time.value = ajaxRequ ...

Transfer the "file" from the busboy to the GM for FTP uploading

I'm looking to resize an uploaded image using nodejs and send it via ftp. I'll be utilizing nodejs, busboy, GraphicsMagick, and jsftp. var uploadFile = function(dir, req, cb) { req.busboy.on('file', function(fieldname, file, filename, ...

The process of uploading a file is interrupted by an AJAX Timeout

My HTML form includes a file input field that utilizes AJAX to upload the selected file, complete with a progress bar. However, I encountered an issue where the request would hang without any response. To prevent this from happening in the future, I aim t ...

Can you explain the distinction between the controls and get methods used with the FormGroup object?

I have encountered an interesting issue with 2 lines of code that essentially achieve the same outcome: this.data.affiliateLinkUrl = this.bookLinkForm.controls['affiliateLinkUrl'].value; this.data.affiliateLinkUrl = this.bookLinkForm.get(' ...

Exploring JavaScript and Node.js: Deciphering the choice of prototype.__proto__ = prototype over using the

Currently exploring the Express framework for node.js and noticed that all the inheritance is achieved through: Collection.prototype.__proto__ = Array.prototype; Wouldn't this be the same as: Collection.prototype = new Array; Additionally: var ap ...

Combine all the HTML, JavaScript, and CSS files into a single index.html file

So here's the situation - I am utilizing a C# console application to convert four XML files into an HTML document. This particular document will be circulated among a specific group of individuals and is not intended to be hosted or used as a web app; ...

Chrome triggers Skrollr 'relative top-bottom' animations prematurely

I am working with multiple relative positioned divs stacked on top of each other, each set to a height of 100% using jQuery upon loading. Within these relative positioned divs, there is a fixed div containing the content. Using skrollr, I have implemented ...

Limit the user to entering a maximum of (40) characters in the textarea

To enforce a character limit of 40 characters in a text area, I have implemented the following JavaScript function to trigger on the textarea's onKeyUp event: However, a problem arises when pasting content exceeding 40 characters into the textarea - ...

Exploring the realm of JavaScript and finding the perfect spot

Looking to learn more about locating elements and using javascript effectively. For example, when a user clicks on an element, I want to display a menu right below it. I also need to consider scenarios where the element is located at the edge of the page ...

Steps for handling errors in Node.js when the query result rowCount is 0 and throwing an error in response

If the rowcount is 0, I need to send a response as failed. If the rowcount is 1, I need to send a success status. Can someone please assist me with this? When I try to print (client.query), it displays the result in JSON format (refer to attached image). ...

Performing complex joins in MongoDB using multiple sub documents

I am managing two unique collections, Users collection: { "userId": 1, "name": 'Alice', "profile": 'alice.png' }, { "userId": 5, "name": 'Bob', "profile": 'bob.png' }, { "userId": 10, ...

Tips for customizing the CSS of the ss-multiselect-dropdown component

Is it possible to customize the style of ss-multiselect-dropdown in Angular 7? I am currently using ngb multiselect and would like to know how to override the CSS for this component. ...

Is it possible to hide a menu by removing a class when the user clicks outside the menu?

I've come across a lot of information about how to close a menu when clicking outside of it, but my question is, can the following code be simplified to something like if you don't click on #menu > ul > li > a then removeClass open. Can ...

Express.js not redirecting to Angular route, app not starting

I have the following setup in my node.js app.js: app.use('/', routes); app.get('some_api', routes.someApi); app.use(function (req, res) { res.sendFile(path.join(__dirname, 'public', 'index.html')); }); Additio ...

Ensuring the presence of an attribute within an AngularJS Directive

Is it possible to determine if a specific attribute exists in a directive, ideally using isolate scope or the attributes object as a last resort? If we have a directive like this <project status></project>, I would like to display a status ico ...

The Typescript Select is displaying an incorrect value

Here's the code snippet I've been working with: <select #C (change)="changeSelect(zone.id, C.value)"> <option *ngFor="let town of townsLocal" [attr.value]="town.data" [attr.selected]="town.data === zone.town && 'selected& ...

How can I automatically copy a highlighted link in HTML?

I am attempting to implement a feature where users can click on a link and have it automatically copied. For example, I want it to appear like this: "UPI ID: david@okidfcbank". In this case, the link should be highlighted in blue. This is the code I have ...