Setting a timeout for loading an external JavaScript file that is currently inaccessible

Using JavaScript, I am integrating content from a PHP file on a different server. Unfortunately, this external service can be unreliable at times, causing delays in loading or not loading at all.

I am looking for a way in JavaScript to attempt retrieving the external data for a specific duration before deciding to stop including the JavaScript content.

Answer №1

If you are referring to

<script src="javascript.php"></script>

then the answer is no, which is why JSONP may not be the best solution in these situations.

However, you could potentially utilize setTimeout to test for a specific variable in the JavaScript code and trigger an error if the variable or function is not found.

Here's an example:

<script>
var start = new Date();
var tId;
function testFunction() {
  var end = new Date();
  if ((end.getTime() - start.getTime()) > 10000) {
    alert('Timeout reached: Aborted')
  }
  else if (someFunction) { // Ensuring someFunction exists in the external JS
    someFunction()
  }
  else tId = setTimeout(testFunction, 1000)
}
</script>

<script src="javascript.php"></script>

Answer №2

<script type="text/javascript">
var jsLoaded = false;
setTimeout("callback()", 2000);
function callback() {
    if (!jsLoaded) {
        alert("Oops! JavaScript still hasn't loaded after 2 seconds.");
    } else {
        alert('Success: Loaded');
    }
}
</script>
<script type="text/javascript" id="foo" src="url.js" onload="jsLoaded=true"></script>

Now, the challenge is to halt the script loading process. Removing the <script> element from the DOM hasn't stopped it...

If your .js file is on the same domain, consider using the AJAX technique to load the JavaScript externally (refer to this link)

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

Encountered Error: Failed to inject additional dependencies

Attempting to manage my views using state (ui.router) has hit a roadblock. The addition of extra dependencies to the module is triggering the following error: Uncaught Error: [$injector:modulerr] This error is causing my states to break. var MyApp = a ...

Utilizing a function argument within the :not() selector

I am currently working towards the objective of selecting all elements in my document except for those within a specific class. This is what I have come up with so far: var x = document.querySelectorAll(":not(.myParameter)"); My aim is to make 'myPa ...

Using the Composition API in Vue 3: Guide to invoking a method within the template to retrieve a return value

Within my template, I have implemented the following code snippet: <template> {{ getScope(scope.row, itemIn.field) }} </template> For the Option API section, I've included: methods: { getScope(data, key) { const str ...

What is the method to combine multiple style values in vue.js?

Is there a way to create a div with a box shadow where the values can be changed using a slider? I am having trouble using more than one value stored in a data variable. Any suggestions on how to achieve this? <div :style="{ borderRadius: x_axis y_ ...

Having trouble with downloading a node module?

I encountered an issue while trying to download the node-sass node module. The error message I received was as follows: To download the node-sass module, use the command: npm install --save-dev node-sass Error Binary has a problem: Error: \?\C: ...

Retrieve the selected status and value of the option that initiates a multiple selection change event

Is there a way to track only the value that has been added or removed from a selection, rather than getting an array of all selected values? How can I monitor each individual option within a selector to identify which one has changed, instead of looking a ...

One helpful tip for adjusting the size of a UI chip on the fly

I am attempting to adjust the size of a UI chip dynamically based on the font size of its parent elements using the em unit in CSS. My objective is to achieve something like this: style={{size:'1em'}} The issue I'm encountering: The chip e ...

Basic Hover Effect in Javascript

Looking at this snippet of HTML: <div id="site-header-inner"> <div id="header-logo"> <?php echo wp_get_attachment_image(get_field('header_logo','options'),'full'); ?> </div> <div id= ...

What is the best way to display a mongodb _id in HTML using AJAX?

Using an ajax function to fetch employees using the code provided below, I am attempting to incorporate the mongodb _id field into the checkbox id attribute. However, after rendering in the browser, the output appears as follows: <input id="[object Obj ...

A streamlined method for generating an array containing all numerical string values

I'm looking to generate an array of digits in JavaScript. Currently, I have hard-coded it like this: const digitGeneration = ['0', '1', '2', '3', '4', '5', '6', '7', &apo ...

Tips for categorizing items retrieved from .getJSON based on their category property

Looking to display a menu of coffee items with their respective parent categories on the page? Here's how you can start: Category Title Item Item Item Item Category Title Item Item This is what my data model looks like: { "menuItems": [ ...

Preventing the display of AngularJS HTML tags while the app is being loaded

I am new to AngularJS (using version 1.5.8) and I am currently following the tutorials provided on docs.angularjs.org/tutorial. Below is the HTML code snippet: <div class="jumbotron"> <h1>{{application_name | uppercase }}</h1> ...

Creating a variable to store the data retrieved from a package

Imagine you have a functioning code snippet like this: const myPackage = require('myPackage'); myPackage.internal_func(parameter).then(console.log); This outputs a JSON object, for example: { x: 'valX', y: 'valY' } ...

Pressing "Enter" initiates the submission of the form

My webpage contains a stylish GIF displayed as a button within a div. The script inside the div triggers a click event when the ENTER key is pressed, using $(this).click(). This click action has its own functionality. Everything functions smoothly in Fire ...

Getting form field values with JQuery

I am currently facing an issue with a form field in HTML. Here is the code snippet: <form id="tasklist"> <input type="text" id="name" ...></input> ... additional form elements go here ... </form> Although I am trying to retrie ...

Displaying selected values in a Multi Select Listbox upon submission of the same form when an error occurs

When the page is first loaded: Retrieve the values from the table field and store them in a variable If the field is blank, do not take any action Populate the listbox with default custom values When the form is submitted (on the same page) and multipl ...

What is the method to change between input sources in php?

Imagine this scenario: when a user clicks on a specific button, I want them to be presented with either a dropdown list or an input field. This decision would allow the user to choose an existing item or create a new one. <select name="choose[rowId]"&g ...

The server could not locate the URL /about-us that was requested

Upon completing the export process, I am facing an issue on the host where a message is not displaying when I manually enter the link or refresh the page. I have both the server.js and the next module in place. Is there anything else that needs to be done? ...

Why is an additional return statement necessary in Angular when attempting to retrieve data from a custom service?

As a newcomer to javascript and angular, I have successfully created a custom service in angular that connects to a URL and retrieves information. My goal is to return response.data instead of just the response itself. var getAlldatas = function($http) ...

Use JavaScript and PHP to retrieve a value from an array and dynamically populate select options based on that value

In my PHP code, I have two arrays structured like this: Array ( [0] => 11 [1] => 11 [2] => 11 [3] => 11 [4] => 11 [5] => 187 ) Array ( [0] => 118 [1] => 112 [2] => 85 [3] => 81 [4] ...