javascript 推迟内联javascript执行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20180556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:57:27  来源:igfitidea点击:

Defer inline javascript execution?

javascriptjqueryhtml

提问by ojek

In my website I have many inline javascript snippets. Most of them require jquery and similar stuff.

在我的网站中,我有许多内联 javascript 代码段。他们中的大多数都需要 jquery 和类似的东西。

But I would like to defer jquery load to after the page was rendered. And that means, that my inline javascript would execute, before jquery was loaded. Is there anything I can do about it? I am looking for easy to implement solutions (I also cannot move my inline javascript since it is automatically generated while page is being prepared for the user).

但我想将 jquery 加载推迟到页面呈现后。这意味着,我的内联 javascript 将在加载 jquery 之前执行。有什么我可以做的吗?我正在寻找易于实施的解决方案(我也无法移动我的内联 javascript,因为它是在为用户准备页面时自动生成的)。

采纳答案by troelskn

It would be much better if you could place your javascript at the end of the document. Sprinkling your source with small inline javascript snippets is a killer on page performance.

如果你能把你的 javascript 放在文档的末尾会好得多。用小的内联 javascript 代码片段散布您的源代码是页面性能的杀手。

That said, you could create an array and push functions on this array. Then, at the end of your page, right after you load jquery, loop over the array and execute each function.

也就是说,您可以创建一个数组并在该数组上推送函数。然后,在页面的末尾,在加载 jquery 之后,循环遍历数组并执行每个函数。

E.g.:

例如:

<html>
  ...
  <script>window.loadEvents = [];</script>
  ...
  <script>loadEvents.push(function() { alert("inline code here"); });</script>
  ...
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>$.each(loadEvents, function(_,f) { f(); });</script>
</html>

However - as I said - it would be better to just push all the script elements into the bottom of the page, instead of switching back and forth between html and javascript. The rendering performance will be severely degraded, if you do this.

但是 - 正如我所说 - 最好将所有脚本元素推送到页面底部,而不是在 html 和 javascript 之间来回切换。如果这样做,渲染性能将严重下降。

回答by Alvaro Montoro

You could simulate a defer by setting the typeof the inline scripts to one that would not be processed by the browser like text/example, and the cloning those scripts at the end of the document replacing the typewith text/javascript.

你可以通过设置模拟延迟type内嵌脚本一个不会被喜欢的浏览器来处理的text/example,并在文件替换结束的克隆那些脚本typetext/javascript

The code that processes all the text/examplesis really simple:

处理所有这些的代码text/examples非常简单:

window.addEventListener("load", function() {

    var arr = document.querySelectorAll("script[type='text/example']");
    for (var x = 0; x < arr.length; x++) {
        var cln = arr[x].cloneNode(true);
        cln.type = "text/javascript";
        document.querySelectorAll("body")[0].appendChild(cln);
    }

});

Or if you prefer to use jQuery (you'll have to add this script afterincluding the jQuery file):

或者,如果您更喜欢使用 jQuery(您必须包含 jQuery 文件添加此脚本):

$(function() {
    $("script[type='text/example']").each(function() {
        $(this).clone().attr("type","text/javascript").appendTo("body"); 
    });
});

This code waits until the page has loaded, then selects all the scripts with type text/example, and copies them at the end of the bodywith a type of text/javascriptso they are executed normally.

此代码等待页面加载完毕,然后选择所有类型为 的脚本text/example,并在类型为 的末尾复制它们bodytext/javascript以便它们正常执行。

For example:

例如:

...
<script type="text/example">
    console.log("I am before the h1");
</script>

<h1>Page Title</h1>

<script type="text/javascript">
    console.log("I am after the h1");
</script>
...

Will result in these messages in the console:

将在控制台中导致这些消息:

I am after the h1

I am before the h1

我在 h1 之后

我在h1之前

You can see a running demo on this JSFiddle: http://jsfiddle.net/rqckwc79/

你可以在这个 JSFiddle 上看到一个正在运行的演示:http: //jsfiddle.net/rqckwc79/



Pros of this solution:

该解决方案的优点:

  • It is a cross-browser solution.
  • The code is valid HTML/JavaScript.
  • It works in strict mode.
  • 这是一个跨浏览器的解决方案。
  • 代码是有效的 HTML/JavaScript。
  • 它在严格模式下工作。

Cons of this solution:

此解决方案的缺点:

  • You need to have control over the inline scripts to change the type.
  • As troelskn said, performance would be worse than moving all the code to the bottom (but I understand there are situations in which that is not possible).
  • It doesn't work on older IE versions (although the code could be modified to support them).
  • 您需要控制内联脚本以更改type.
  • 正如 troelskn 所说,性能会比将所有代码移到底部更糟糕(但我理解在某些情况下这是不可能的)。
  • 它不适用于较旧的 IE 版本(尽管可以修改代码以支持它们)。