Skip to content

Instantly share code, notes, and snippets.

@tomerof
Created May 24, 2023 06:28
Show Gist options
  • Save tomerof/54c30b25556a902b0ffe22528b48e6e8 to your computer and use it in GitHub Desktop.
Save tomerof/54c30b25556a902b0ffe22528b48e6e8 to your computer and use it in GitHub Desktop.
javascript load another script dynamically

To conditionally load a JavaScript script from a URL in JavaScript, you can use the following approach:

function loadScript(url, condition, callback) {
  if (condition) {
    var script = document.createElement('script');
    script.src = url;
    script.onload = callback;
    document.head.appendChild(script);
  } else {
    // Condition is false, do something else or skip loading the script
    callback();
  }
}

// Example usage
var isConditionMet = true; // Change this value based on your condition

loadScript('https://example.com/script.js', isConditionMet, function() {
  // Script has loaded, execute your code here
});

In the code above, the loadScript function takes three parameters: url (the URL of the script), condition (a boolean indicating whether the script should be loaded), and callback (a function to be executed once the script has loaded).

Inside the loadScript function, it checks the condition parameter. If the condition is true, it creates a new <script> element, sets its src attribute to the provided URL, attaches an onload event handler to execute the callback function when the script has finished loading, and appends the <script> element to the <head> of the document.

If the condition is false, it can either perform some other action or skip loading the script altogether. In the example code, it simply calls the callback function immediately.

You can modify the isConditionMet variable to evaluate your own condition, determining whether to load the script or not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment