The JavaScript code is executing before the SPFX Web Part has finished loading on the SharePoint page

I recently set up a Sharepoint Page with a custom masterpage, where I deployed my SPFx Webpart that requires certain javascript files.

While the Webpart functions correctly at times, there are instances when it doesn't work due to the javascript being called before SPFx is loaded in the DOM. I even attempted placing the javascript in the custom masterpage, but the issue persisted.

Upon researching online, I came across this helpful Reference.

To address the issue, I modified the javascript function by calling it on the load event instead of the ready function. This resolved the problem in Chrome, but unfortunately, it's still not functioning properly in IE and Firefox.

I am wondering if there might be another approach to achieve the desired outcome.

Answer №1

Essentially, if you find yourself just waiting around, one approach is to listen for the DOMContentLoaded event. This handy event listener is compatible across different browsers, including Firefox and even Internet Explorer 9.

// Method 1
    window.addEventListener("DOMContentLoaded", function () {
        console.log('ready')
    }, false);

If your SPFx code dynamically creates elements later on, you can wait for those elements to be present in the DOM. Check whether they exist before executing your desired function like this:

// Method 2
// Wait for the element to appear in the DOM
const waitForElement = (selector, timeout = 1000, callback) => {
    const interval = setInterval(() => {
        const element = document.querySelector(selector);
        if (element) {
            clearInterval(interval);
            // Execute desired functionality
            callback()
        } else {
            console.log('Element not found yet')
        }
    }, timeout);
};

// Simulate delay of 3 seconds and insert element into the DOM
setTimeout(() => {
    document.body.innerHTML = document.body.innerHTML + "<div id='test-div'>TEST</div>";
}, 3000);

const myFunction = () => console.log('Element found in the DOM');

waitForElement('#test-div', 1000, myFunction)

P.S. It's advisable to implement a fallback mechanism in case the element remains elusive after a certain duration, preventing the interval from running indefinitely.

Answer №2

To manage how external scripts are loaded, you can utilize the async and defer attributes.

According to information from the MDN web docs:

defer: This attribute is a Boolean flag that instructs the browser to execute the script after parsing the document but before triggering DOMContentLoaded.

async: This attribute serves as a Boolean indicator for the browser to load the script asynchronously whenever possible.

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

Navigating with React Router using URL parameters

After implementing react router with a route path taskSupport/:advertiserId that includes parameters, I encountered an issue when trying to access the link http://localhost:8080/taskSupport/advertiserId. My browser kept returning 404 (Not found) errors for ...

The output of jquery's val() function will not show the actual value

Is it proper to use html() for setting content in non-form elements like divs? This question has come up a few times, which I wasn't aware of. I've been working on setting a value after fetching comments through a $.ajax call. When I check the v ...

Unexpected behavior: Promise.catch() fails to catch exception in AngularJS unit test

During the process of writing Jasmine unit tests for my Typescript app and running them via Resharper, I encountered an issue with executing an action when the handler throws an exception: describe("Q Service Test", () => { var q: ng.IQService; ...

Run XQuery dynamically in JavaScript and store the outcome in a JavaScript variable

Looking to achieve the following: Running a dynamic XQUERY stored in a JavaScript variable example var myxquery = For Channels.Channel where Channel/availability = yes And Channels.Channel/Label = 'CNN' Return EXIST(Channels.Channel/Id)&apo ...

Heroku is showing an Error R10 (Boot timeout) message, indicating that the web process was unable to bind to the designated $PORT within one minute of launching

Encountering an error while trying to deploy my first node project on Heroku. Here is the error message: 2020-09-29T04:24:09.365962+00:00 app[web.1]: production 2020-09-29T04:24:09.415266+00:00 app[web.1]: server is listening at port 40890 2020-09-29T04:24 ...

Create a compressed package of a Vue project that can easily be inserted into a Blogger blog post as a single HTML file

Is there a way to package all the files related to a Vue.js project (HTML, JavaScript, CSS) into one single HTML file for easy deployment on a Blogger Blogspot post? In the past, a question similar to this was asked regarding bundling files into a single ...

Empty req.params in nested ExpressJS routers

I have a unique routing system that relies on the directory structure of my 'api' folder to automatically configure routes. However, I encountered an issue where the req.params object is undefined in the controller when using a folder name as a r ...

Does npm run use a separate version of TSC?

I am encountering an issue with my VS Code and Node.js project that uses Typescript. Within my package.json file's script block, there is an entry: "build-ts": "tsc" When I run simply tsc on the integrated terminal command line, the compilation proc ...

Manipulating the "placeholder" attribute with Knockout.js and JSON data

Is it possible to use the placeholder attribute with data-bind? I am encountering an error message ([object object]). Can someone help me figure out how to properly utilize it? html: input id="comments" class="form-control" data-bind="attr: { placeholde ...

Obtain a string in JSON format upon clicking in Angular 2

I am working on extracting the title from a json response using a click event. Currently, I can retrieve all the titles when the button is clicked, but I am looking for a way to obtain a specific title based on the button or a href that the user has clicke ...

Javascript code fails to execute properly on IE8

I have a scenario where I am working with two drop-down menus. When the user selects an option from one menu, it should dynamically change the options in the other menu. However, I'm facing an issue with Internet Explorer where the second drop-down me ...

Calculating the time difference between two dates in the format yyyy-MM-ddTHH:mm:ss.fffffff can be done by following these steps

Can someone help me figure out how to calculate the difference in days between the date and time 2021-02-23T08:31:37.1410141 (in the format yyyy-MM-ddTHH:mm:ss.fffffff) obtained from a server as a string, and the current date-time in an Angular application ...

Puppeteer: What is the best way to interact with a button that has a specific label?

When trying to click on a button with a specific label, I use the following code: const button = await this.page.$$eval('button', (elms: Element[], label: string) => { const el: Element = elms.find((el: Element) => el.textContent === l ...

Exploring jQuery.each: A guide to navigating JSON objects

As a beginner in working with JSON, I am struggling to iterate over a JSON response received via AJAX. My objective is to extract and loop through checkbox values retrieved from a database table such as 2,3,7,9,3. However, I am currently facing difficultie ...

Issues with select options not functioning correctly in knockout framework

Currently, I am engaged in a project where data is being retrieved from an API. The main task at hand is to create a dropdown list using select binding. In order to do so, I have defined an observable object to hold the selected value within my data model. ...

The font remains the same despite the <Div style=> tag

I have a script that loads external HTML files, but I am facing an issue with changing the font to Arial. The script is as follows: <script type="text/javascript"> $(document).ready(function(){ $("#page1").click(function(){ ...

What is the best way to modify a constant array in Angular?

Hello team, I'm fresh to working with angular and I have a TypeScript file that contains a list of heroes: export const HEROES: Hero[] = [ { id: 11, name: 'Dr Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: 'Bombas ...

What is the functionality of observable in Angular? The 'includes' property is not present in the 'Observable' type

I am currently diving into the world of Angular5 and I have been using Firebase to fetch data for my page display. While researching how to retrieve data from Firebase using AngularFire, I found that many examples were outdated. Eventually, I learned that ...

Is it possible to implement a custom sign-in form for AWS Cognito?

Is it possible to replace the AWS Cognito hosted UI with a custom form in my Next.js app that utilizes AWS Cognito for authentication? import { Domain } from "@material-ui/icons"; import NextAuth from "next-auth"; import Providers fro ...

What is the process for deducting the ordered quantity from the available quantity once an order is confirmed

Although I'm not a fan of hard coding, I've been struggling to find a solution to my problem and some explanations are just not clicking for me. The issue at hand involves three data products in the cart, product details, and placed order data f ...