Set timeout for third-party file request using jQuery

I am trying to integrate a third-party script file into a new website.

I am currently adding a script tag to the DOM for this third-party script file in the finished document:

$(document).ready( function() { var extScript = document.createElement('script'); extScript.type = 'text/javascript'; extScript.src = 'http://third-party.com/scriptfile.js'; $('head').append(extScript); }); function extScriptCallback() { $('#extWidgetContainer').show(); } 

But sometimes a third-party script file request is turned off or takes a lot of time.

So, for best practice, I want to provide alternative content if the external script takes more than, for example, 10 seconds to load.

How do I achieve this? I looked at the built-in JavaScript setTimeout () function, as well as the jQuery delay () function, but I'm not sure what I should use - or how.

Thanks for any suggestions.

+4
source share
1 answer

There are several ways you can approach this. The first method is to check the timer for a function or variable provided by a third-party script. If it is not available when you check it, it is not loaded yet:

 $(document).ready( function() { var extScript = document.createElement('script'); extScript.type = 'text/javascript'; extScript.src = 'http://third-party.com/scriptfile.js'; window.setTimeout(function () { if ("thirdPartyFuncName" in window) alert("loaded"); else alert("Not loaded yet"); }, 10000); // 10 secs $('head').append(extScript); }); 

Another way you could go is to investigate the onload and onreadystatechange events provided by browsers. AFAIK, onload widely used, so you can do something like this:

 var timer; extScript.onload = function () { clearTimeout(timer); } timer = window.setTimeout(function () { alert("not loaded"); }, 10000); // 10 secs 

The disadvantage of this approach is that the load event will fire even if the script has a syntax error, so I still think that the first approach is your best choice, because it checks for the existence of functionality.

+2
source

Source: https://habr.com/ru/post/1308460/


All Articles