slow-loading javascript include blocks rest of site
I have a site with a third-party Javascript include coming from a开发者_StackOverflow社区n external URL. However, it frequently loads very slowly (if at all). It is a tracking service used by our marketing team, so I can't remove it (I have suggested it!).
Currently it's included at the end of my page template with a very simple
<script src='http://remoteurl/'></script>
All the other scripts on the page wait until it has loaded before executing anything, meaning that any JS widgets I'm using don't work until it loads. If it times out, they never run.
So the performance problems of an external site are causing issues on for our site.
The frustrating thing about it is that the site doesn't need this script to load for everything else to function. So is there a way to load it such that it doesn't block the rest of the site's scripts from running if it fails?
(I've tried the defer attribute, but although this affects the execution sequence, it doesn't change the fact that everything has to load before anything happens)
Thanks for any advice.
See this question for that. The approach is to create the script element dynamically onload, so it doesn't block or delay the load itself.
Can you add code at the very end of the page that adds the script tag to the page instead of adding the script tag manually? This is how Google Analytics handles it. That way the rest of (your) code runs before the tracker code is even added to the page.
Sample:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("tracker-id-removed");
pageTracker._trackPageview();
} catch (err) { }
</script>
精彩评论