Verify External Script Is Loaded
If the script creates any variables or functions in the global space you can check for their existance:
External JS (in global scope) --
var myCustomFlag = true;
And to check if this has run:
if (typeof window.myCustomFlag == 'undefined') {
//the flag was not found, so the code has not run
$.getScript('<external JS>');
}
Update
You can check for the existence of the <script>
tag in question by selecting all of the <script>
elements and checking their src
attributes:
//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
return ($(this).attr('src') == '<external JS>');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
$.getScript('<external JS>');
}
Or you can just bake this .filter()
functionality right into the selector:
var len = $('script[src="<external JS>"]').length;
Detect whether external script has loaded
Thanks for the assistance above, especially ngmiceli for the Steve Souders link!
I decided to take what's probably a "lazy" approach, and also forego the "loading" message:
$(document).ready(function(){
if ($('.jt_job_list').length === 0){
$('#job-board').html("<p>We're sorry, but the Job Board isn't currently available. Please try again in a few minutes.</p>");
};
});
Pretty simple, but I'm looking to see if an element with the .jt_job_list
class is in the dom. If it isn't, I display an error message.
How to know if a JavaScript (script) was loaded?
I recommend jQuery, it's so easy with that. Life is too short for coding things like that yourself (you will waste hours for supporting all browsers).
$.ajax({
url: "/script.js",
dataType: "script",
success: function() {
console.log("script loaded");
}
});
EDIT:
It's even easier (example from jQuery docs):
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
console.log(data); // Data returned
console.log(textStatus); // Success
console.log(jqxhr.status); // 200
});
You can also chain done and fail to have additional callbacks:
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log(textStatus);
})
.fail(function(jqxhr, settings, exception) {
console.log("loading script failed.");
});
Load jQuery asynchronously
<script src="path/to/jquery"></script>
<script>
function wait(method) {
if (window.$) {
method();
} else {
setTimeout(function () { wait(method); }, 100); // check every 100ms
}
}
// wait for jQuery
wait(function() {
// jQuery has loaded!
$("#foo").doSomething();
// you can now load other scripts with jQuery:
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log(textStatus);
})
.fail(function(jqxhr, settings, exception) {
console.log("loading script failed.");
});
}
</script>
Check if external js script already in component Angular 2
use
document.querySelector('script[src="https://www.google.com/recaptcha/api.js"]');
to test if the script tag already exists
or check for the existence of window.__google_recaptcha_client
Check if a JavaScript file was loaded
Try window.onload
. This event fires after all scripts are loaded.
function init() {
// your code
}
window.onload = init;
Loading Javascript Dynamically and how to check if the script exists
Listening for events on script elements is not considered reliable (Source). One option that comes to mind is to use setTimeout()
to poll for a variable that you expect to be defined in your external script. After x
seconds, you could timeout your poll and consider the script as broken.
External Script: file.js:
var MyLibrary = { };
Main document:
var poll;
var timeout = 100; // 10 seconds timeout
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'file.js';
document.body.appendChild(script);
poll = function () {
setTimeout(function () {
timeout--;
if (typeof MyLibrary !== 'undefined') {
// External file loaded
}
else if (timeout > 0) {
poll();
}
else {
// External library failed to load
}
}, 100);
};
poll();
Related Topics
Document.Queryselector Always Returns Null
How to Remove Image from Browser Cache
Javascript/Dom: How to Remove All Event Listeners of a Dom Object
Modify Classname When Element Is Clicked in React
How to Refresh an Angular Component
Prevent User from Typing in Input At Max Value
Why Is It a Bad Practice to Return Generated HTML Instead of Json or Is It
Hosting Your Own JavaScript Scripts Files (Other Than Jquery) on Fast Free Cdns Like Google
Reactjs Dynamic Drop Down Populated With Map Function
Detect Click into Iframe Using JavaScript
How to Close Current Tab in a Browser Window
Remove Parameter from Url Via Regex
How to Count Duplicate Value in an Array in JavaScript
How to Make a Modal Popup to Take an Input Value Using Jquery or JavaScript
Regular Expression Which Matches a Pattern, or Is an Empty String
If Check Box Checked Disable Other, If Unchecked Enable All in React