简体   繁体   English

页面加载后加载脚本?

[英]Loading scripts after page load?

I work with an advertising company, where we tag certain pages to track activity.我与一家广告公司合作,我们在其中标记某些页面以跟踪活动。 A client of mine wants to fire off a javascript tag to track activity AFTER the page has finished loading entirely (to prevent the page content from loading slowly due to slow tag load times).我的一个客户想要在页面完全加载完成后触发 javascript 标记以跟踪活动(以防止由于标记加载时间缓慢而导致页面内容加载缓慢)。

An example tag that should load AFTER the page has fully loaded is:应在页面完全加载后加载的示例标记是:

<script>document.write('<s'+'cript language="JavaScript" src="http://jact.atdmt.com/jaction/JavaScriptTest"></s'+'cript>')</script>

I was looking at some stackoverflow threads and I came across the below implementation which I think will work:我正在查看一些stackoverflow线程,并且遇到了以下我认为可行的实现:

window.onload = function(){
  <script language="JavaScript" src="http://jact.atdmt.com/jaction/JavaScriptTest"></script>
};

I tested this on my own webpage and I did get the tag to fire off, but I'm wondering if there are any alternate or more robust methods, ideally using jquery of some kind.我在自己的网页上对此进行了测试,并且确实启动了标签,但我想知道是否有任何替代或更强大的方法,最好使用某种 jquery。

Below is a sample implementation that the client tried, but it seems to break their page:下面是客户端尝试的示例实现,但它似乎破坏了他们的页面:

<script>
jQuery(window).load(function () {$('<script language="JavaScript" src="http://jact.atdmt.com/jaction/JavaScriptTest"></script>').insertAfter('#div_name');});
</script>

I haven't done JQuery in a while and was hoping I could get some input from other members here.我有一段时间没有做 JQuery 了,希望我能从这里的其他成员那里得到一些意见。 Is there any other way I can call the above script after page load using JQuery?在使用 JQuery 加载页面后,我还有其他方法可以调用上述脚本吗?

Thanks,谢谢,

So, there's no way that this works:所以,这是不可能的:

window.onload = function(){
  <script language="JavaScript" src="http://jact.atdmt.com/jaction/JavaScriptTest"></script>
};

You can't freely drop HTML into the middle of javascript.您不能随意将 HTML 放入 javascript 的中间。


If you have jQuery, you can just use:如果你有 jQuery,你可以使用:

$.getScript("http://jact.atdmt.com/jaction/JavaScriptTest")

whenever you want.无论你什么时候想要。 If you want to make sure the document has finished loading, you can do this:如果要确保文档已完成加载,可以执行以下操作:

$(document).ready(function() {
    $.getScript("http://jact.atdmt.com/jaction/JavaScriptTest");
});

In plain javascript, you can load a script dynamically at any time you want to like this:在普通的 javascript 中,您可以随时动态加载脚本:

var tag = document.createElement("script");
tag.src = "http://jact.atdmt.com/jaction/JavaScriptTest";
document.getElementsByTagName("head")[0].appendChild(tag);

The second approach is right to execute JavaScript code after the page has finished loading - but you don't actually execute JavaScript code there, you inserted plain HTML.第二种方法是在页面加载完成后执行 JavaScript 代码是正确的 - 但实际上您并没有在那里执行 JavaScript 代码,而是插入了纯 HTML。
The first thing works, but loads the JavaScript immediately and clears the page (so your tag will be there - but nothing else).第一件事有效,但会立即加载 JavaScript 并清除页面(因此您的标签将在那里 - 但没有别的)。
(Plus: language="javascript" has been deprecated for years, use type="text/javascript" instead!) (另外:language="javascript" 已被弃用多年,请改用 type="text/javascript"!)

To get that working, you have to use the DOM manipulating methods included in JavaScript.为了让它工作,你必须使用 JavaScript 中包含的 DOM 操作方法。 Basically you'll need something like this:基本上你需要这样的东西:

var scriptElement=document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = filename;
document.head.appendChild(scriptElement);

Focusing on one of the accepted answer 's jQuery solutions, $.getScript() is an .ajax() request in disguise .专注于已接受答案的 jQuery 解决方案之一, $.getScript()伪装.ajax()请求 It allows to execute other function on success by adding a second parameter:它允许通过添加第二个参数成功执行其他函数:

$.getScript(url, function() {console.log('loaded script!')})

Or on the request's handlers themselves, ie success ( .done() - script was loaded) or failure ( .fail() ):或者在请求的处理程序本身上,即成功( .done() - 脚本已加载)或失败( .fail() ):

 $.getScript( "https://code.jquery.com/color/jquery.color.js", () => console.log('loaded script!') ).done((script,textStatus ) => { console.log( textStatus ); $(".block").animate({backgroundColor: "green"}, 1000); }).fail(( jqxhr, settings, exception ) => { console.log(exception + ': ' + jqxhr.status); } );
 .block {background-color: blue;width: 50vw;height: 50vh;margin: 1rem;}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="block"></div>

For a Progressive Web App I wrote a script to easily load javascript files async on demand.对于渐进式 Web 应用程序,我编写了一个脚本来轻松按需异步加载 javascript 文件。 Scripts are only loaded once.脚本只加载一次。 So you can call loadScript as often as you want for the same file.因此,您可以根据需要随时为同一个文件调用 loadScript。 It wouldn't be loaded twice.它不会被加载两次。 This script requires JQuery to work.此脚本需要 JQuery 才能工作。

For example:例如:

loadScript("js/myscript.js").then(function(){
    // Do whatever you want to do after script load
});

or when used in an async function:或在异步函数中使用时:

await loadScript("js/myscript.js");
// Do whatever you want to do after script load

In your case you may execute this after document ready:在您的情况下,您可以在文档准备好后执行此操作:

$(document).ready(async function() {
    await loadScript("js/myscript.js");
    // Do whatever you want to do after script is ready
});

Function for loadScript: loadScript 函数:

function loadScript(src) {
  return new Promise(function (resolve, reject) {
    if ($("script[src='" + src + "']").length === 0) {
        var script = document.createElement('script');
        script.onload = function () {
            resolve();
        };
        script.onerror = function () {
            reject();
        };
        script.src = src;
        document.body.appendChild(script);
    } else {
        resolve();
    }
});
}

Benefit of this way:这种方式的好处:

  • It uses browser cache它使用浏览器缓存
  • You can load the script file when a user performs an action which needs the script instead loading it always.当用户执行需要脚本而不是始终加载它的操作时,您可以加载脚本文件。

Here is a code I am using and which is working for me.这是我正在使用的代码,它对我有用。

window.onload = function(){
    setTimeout(function(){
        var scriptElement=document.createElement('script');
        scriptElement.type = 'text/javascript';
        scriptElement.src = "vendor/js/jquery.min.js";
        document.head.appendChild(scriptElement);

        setTimeout(function() {
            var scriptElement1=document.createElement('script');
            scriptElement1.type = 'text/javascript';
            scriptElement1.src = "gallery/js/lc_lightbox.lite.min.js";
            document.head.appendChild(scriptElement1);
        }, 100);
        setTimeout(function() {
            $(document).ready(function(e){
                lc_lightbox('.elem', {
                    wrap_class: 'lcl_fade_oc',
                    gallery : true, 
                    thumb_attr: 'data-lcl-thumb', 
                    slideshow_time  : 3000,
                    skin: 'minimal',
                    radius: 0,
                    padding : 0,
                    border_w: 0,
                }); 
            });
        }, 200);

    }, 150);
};

 <script type="text/javascript"> $(window).bind("load", function() { // your javascript event )}; </script>

http://jsfiddle.net/c725wcn9/2/embedded http://jsfiddle.net/c725wcn9/2/embedded

You will need to inspect the DOM to check this works.您将需要检查 DOM 以检查它是否有效。 Jquery is needed.需要jQuery。

$(document).ready(function(){
   var el = document.createElement('script');
   el.type = 'application/ld+json';
   el.text = JSON.stringify({ "@context": "http://schema.org",  "@type": "Recipe", "name": "My recipe name" });

   document.querySelector('head').appendChild(el);
});

To easily "delay" script execution after the page is loaded use 'defer' attribute:要在页面加载后轻松“延迟”脚本执行,请使用 'defer' 属性:

<script src="demo_defer.js" defer></script>

Keep in mind this only works with external scripts (called with 'src' attribute)请记住,这只适用于外部脚本(使用 'src' 属性调用)

Documentation:文档:

https://www.w3schools.com/tags/att_script_defer.asp https://www.w3schools.com/tags/att_script_defer.asp

https://javascript.info/script-async-defer https://javascript.info/script-async-defer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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