简体   繁体   中英

Loading javascript after all other scripts

I'm using a CMS which has a lot of javascript, both in size and quantity.

I'm trying to add iframe.ly to it so that card previews can be generated for posted URLs.

It works perfectly fine on all pages except for ones that have posts (which are the most important), since posts are loaded via a javascript called stream , and it seems that iframely's script is loading before the stream.

I know this is the issue because I can trigger the script directly using iframely.load() , which does the trick. But I need this to happen automatically on every page load.

This is the script that I added to my header: <script defer charset="utf-8" src="//cdn.iframe.ly/embed.js?key=[my-api-key]" ></script>

Iframely offers another option in their docs, which is this:

<script defer type="text/javascript">
    function loadIframelyEmbedJs() {
        // Replace 'iframe.ly' with your custom CDN if available.
        if (document.querySelectorAll("[data-iframely-url]").length === 0
            && document.querySelectorAll("iframe[src*='iframe.ly']").length === 0) return;
        var iframely = window.iframely = window.iframely || {};
        if (iframely.load) {
            iframely.load();
        } else {
            var ifs = document.createElement('script'); ifs.type = 'text/javascript'; ifs.async = true;
            ifs.src = ('https:' == document.location.protocol ? 'https:' : 'http:') + '//cdn.iframe.ly/embed.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ifs, s);
        }
    }
    // Run after DOM ready.
    loadIframelyEmbedJs();
</script>

This is supposed to make iframely "load only when required", as in when embeds are detected in the page. But that doesn't fix the problem either because that too is loaded before the stream.

I don't mind using jquery if needed.

Edit: Removed mentions of the CMS. It adds unnecessary confusion. This is a javascript question.

Fixed it by wrapping it in this function:

<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "//cdn.iframe.ly/embed.js?key=[my-api-key]";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>

Strange that it's so hard to achieve something like this, or find information on how to do it.

Source: Some SEO website that I can't find anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM