I have created a javascript widget that displays popups and anyone can embed it on their websites by pasting a few lines of code before closing </body>
tag.
While configuring it a user can specify that he wants a popup to be displayed after 10 secs of page load. But since my script depends on jQuery
and before executing its main code it must load it first - sometimes script executes its main()
function much later than in 10 secs...
So currently the steps are:
- Web page is loaded (I do not know how much time it will take)
- My script is loaded (I do not know how much time it will take)
- My script loads jQuery if necessary (I do not know how much time it will take)
- Only when jQuery is loaded it starts counting 10 secs and then runs
displayPopup
function
As you can see it's unsafe to run displayPopup
function in 10 secs after $(document).ready
event because it may not load jQuery or itself yet. And it's okay - it's a technical restriction I can not do anything about (right?).
I just need a way to know how much time has passed since $(document).ready
event. And then I will check this number of seconds inside my main()
function and decide if I need to display popup immediately (if page was loaded > 10 secs ago) or wait a few seconds.
Script install code:
<script>
(function() {
var scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.async = true;
scriptTag.src = "https://www.server.com/script.js";
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(scriptTag, s);
})();
</script>
Loading jQuery part of script.js
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.12.4') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"
);
if (script_tag.readyState) {
script_tag.onreadystatechange = function () {
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
}
else {
script_tag.onload = scriptLoadHandler;
}
(document.getElementsByTagName("head")[0] ||
document.documentElement).appendChild(script_tag);
}
else {
jQuery = window.jQuery;
main();
}
function scriptLoadHandler() {
jQuery = window.jQuery.noConflict(true);
main();
}
Main function:
function main() {
setTimeout(function() {
displayPopup();
}, settings['numberOfSeconds'] * 1000);
}