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.