Answer the question
In order to leave comments, you need to log in
Hang a load event on a not-yet-rendered script element in the head?
Treat this question as purely theoretical, please. If we begin to analyze why I needed this, or how it could be done differently, we will go far from the point of interest to me in the direction of an already satisfactorily solved problem.
So. On an HTML page, head
there are several tags within a tag script
. When the code connected through one of them is executed, you can get a link to the corresponding element (well, for example, if in one line:
var script = Array.prototype.slice.call(document.head.getElementsByTagName("script")).pop()
) and attach an event handler to it load
(script.addEventListener("onload", function(){...}, false)
), which will work after the full execution of this script. load
on subsequent elements script
? I mean, those that are rendered for tags that already exist on HTML pages (everything is trivial for dynamically added ones). head
(which is already accessible) is not justified; does not pop up (at least in Firefox). onload
these scripts, of course, do not have an attribute.Answer the question
In order to leave comments, you need to log in
A solution comes to mind:
console.log('Set interval');
var scriptOnLoadInterval = window.setInterval(attachOnLoads, 20);
function attachOnLoads() {
$('script').each(function() {
var script = $(this);
if (!script.data('onload-attached')) {
script.data('onload-attached', true).one('load', onloadHandler);
}
});
};
function onloadHandler() { console.log( $(this).attr('src') ); };
$(function() {
window.clearInterval(scriptOnLoadInterval);
console.log('Clear interval');
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question