How to Detect If JavaScript Files Are Loaded

How to detect if javascript files are loaded?

I don't have a reference for it handy, but script tags are processed in order, and so if you put your $(document).ready(function1) in a script tag after the script tags that define function1, etc., you should be good to go.

<script type='text/javascript' src='...'></script>
<script type='text/javascript' src='...'></script>
<script type='text/javascript'>
$(document).ready(function1);
</script>

Of course, another approach would be to ensure that you're using only one script tag, in total, by combining files as part of your build process. (Unless you're loading the other ones from a CDN somewhere.) That will also help improve the perceived speed of your page.

EDIT: Just realized that I didn't actually answer your question: I don't think there's a cross-browser event that's fired, no. There is if you work hard enough, see below. You can test for symbols and use setTimeout to reschedule:

<script type='text/javascript'>
function fireWhenReady() {
if (typeof function1 != 'undefined') {
function1();
}
else {
setTimeout(fireWhenReady, 100);
}
}
$(document).ready(fireWhenReady);
</script>

...but you shouldn't have to do that if you get your script tag order correct.


Update: You can get load notifications for script elements you add to the page dynamically if you like. To get broad browser support, you have to do two different things, but as a combined technique this works:

function loadScript(path, callback) {

var done = false;
var scr = document.createElement('script');

scr.onload = handleLoad;
scr.onreadystatechange = handleReadyStateChange;
scr.onerror = handleError;
scr.src = path;
document.body.appendChild(scr);

function handleLoad() {
if (!done) {
done = true;
callback(path, "ok");
}
}

function handleReadyStateChange() {
var state;

if (!done) {
state = scr.readyState;
if (state === "complete") {
handleLoad();
}
}
}
function handleError() {
if (!done) {
done = true;
callback(path, "error");
}
}
}

In my experience, error notification (onerror) is not 100% cross-browser reliable. Also note that some browsers will do both mechanisms, hence the done variable to avoid duplicate notifications.

How to know if a JS file is loaded on server side?

Since the script is requested from your server every time a user loads a browser-page you can track who and how often that path is requested.

A simple approach is that it will be present in you request log files. So you can create a script and read your log files every so often.

A second approach is to setup a special rule/location in nginx/apache/which-ever-server-you-are-running

A third approach is to serve the script via CDN that has all these attributes built in (ie. CloudFront)

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;

How to identify a javascript file is loaded successfully in Script

In javascript right under your script tag you could do a check if some function in that file is accessible in your code:

if (myFunction){
// file loaded successfully
}

where myFunction is some function in that file

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;

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>


Related Topics



Leave a reply



Submit