简体   繁体   English

确保我的.JS文件每次都加载到其他人之前

[英]Make sure my .JS file loads every time before others

I have a website where I don't have access to the source but I can manipulate it using Javascript. 我有一个网站,我无法访问源,但我可以使用Javascript操作它。 I have a file called main.js that has been included at the very end of the includes to which I have the access to and I would like to run my custom Javascript code in that file. 我有一个名为main.js的文件,它已被包含在我有权访问的包的最末端,我想在该文件中运行我的自定义Javascript代码。 I have a .JS file with a function called helloWorld() on my server that I would like to load before any $(document).ready() callback fires, because one of the $(document).ready() functions on my website page/pages uses this function. 我有一个.JS文件,在我的服务器上有一个名为helloWorld()的函数,我希望在任何$(document).ready()回调触发之前加载,因为我的$(document).ready()函数之一网站页面/页面使用此功能。

Custom .JS file : 自定义.JS文件

function helloWorld()
{
alert("Hello World");
}

main.js file on the server (Accessible) : 服务器上的main.js文件(Accessible)

//All the JS code that the website uses
..

// My custom javascript code that includes my custom .JS file
$.getScript("helloWorld.js", function()
{
   // Use anything defined in the loaded script...
});

Now I would like the helloWorld() to be loaded whilst the page is loading and before any $(document).ready() functions fired. 现在我希望在页面加载时以及在任何$(document).ready()函数触发之前加载helloWorld() I understand that loading this .JS file while the page is loading will possibly slow down the page load. 我知道在页面加载时加载此.JS文件可能会减慢页面加载速度。 Is there a bullet-proof way of making sure that my custom javascript function will be loaded prior to any $(document).ready() 's? 是否有一种防弹方式确保我的自定义javascript函数将在任何$(document).ready()之前加载? If there is any other way I can achieve this, please do let me know. 如果有任何其他方式我可以实现这一点,请告诉我。 Looking forward to your suggestions. 期待您的建议。

Looks like I found a solution for your problem. 看起来我找到了解决问题的方法。 I wouldn't suggest it, but it's the only way you can load an external script from another one before the DOMContentLoaded event fires. 我不建议它,但它是在DOMContentLoaded事件触发之前从另一个加载外部脚本的唯一方法。

Solution

Since that your main.js script is in the <head> of your document, you can be sure that it will be loaded and executed before any following part of the DOM. 由于您的main.js脚本位于文档的<head>中,因此您可以确保它将在DOM的任何后续部分之前加载和执行。 Given this, you can use a synchronous XMLHttpRequest to load your script and execute it . 鉴于此,您可以使用同步XMLHttpRequest来加载脚本并执行它

This kind of technique has some pros and cons: 这种技术有一些优点和缺点:

  • Pros: you can load and execute any script before DOMContentLoaded , and also multiple scripts sequentially. 优点:您可以在DOMContentLoaded之前加载和执行任何脚本,也可以按顺序加载和执行多个脚本。

  • Cons: your document will be frozen until the requests are completed. 缺点:您的文档将被冻结,直到请求完成。

Not that bad, if your script isn't enormous it will not drastically impact the loading time. 没那么糟糕,如果你的脚本不是很大,它不会对加载时间产生很大的影响。 We can still do it. 我们仍然可以做到。

Implementation 履行

First of all, make sure that your custom.js script is served over a link which will always be reachable, so that your request will not fail. 首先,确保您的custom.js脚本通过始终可访问的链接提供,以便您的请求不会失败。 Also make sure that your main.js script hasn't got async or defer properties, so that it will always be executed in the <head> , before the DOMContentLoaded event. 还要确保你的main.js脚本没有asyncdefer属性,因此它总是在DOMContentLoaded事件之前的<head>执行。

<!-- NOT GOOD -->
<script src="main.js" defer></script>
<script src="main.js" async></script>

<!-- GOOD :) -->
<script src="main.js"></script>

Now that you're ready, in your main.js script you'll need to: 现在你准备好了,在你的main.js脚本中,你需要:

  1. Create and initialize a synchronous XMLHttpRequest object, and send() a GET request to your content.js script. 创建并初始化同步XMLHttpRequest对象,并向您的content.js脚本send() GET请求。

  2. Create a <script> element, and put the result of your request (which is stored in the .responseText property of the request object) inside it. 创建一个<script>元素,并将请求的结果(存储在请求对象的.responseText属性中)放入其中。

  3. Append the script to the <head> to make it run before the DOM is loaded. 将脚本附加到<head>以使其在加载DOM之前运行。

Plus, if you also want your script to be removed right after execution (so it will not be visible to the users), you can: 另外,如果您还希望在执行后立即删除脚本(因此用户无法看到),您可以:

  1. Remove the <script> from the document after it has ran its code. 运行代码后,从文档中删除<script> You'll need to listen for the onload event for this. 你需要为此监听onload事件。

Also, if you want to make your code run completely anonymously, you can wrap it inside an anonymous function to prevent the access to it from the global scope. 此外,如果要使代码完全匿名运行,可以将其包装在匿名function以防止从全局范围访问它。

Here's a quick example of what you'll need to do in your main.js file: 以下是您在main.js文件中需要执行的操作的快速示例:

(function() {
    // Create the request and the script
    var xhr = new XMLHttpRequest(),
        s = document.createElement('script');

    // Send the request to retrieve custom.js
    xhr.open('GET', 'path/to/custom.js', false);
    xhr.send();

    // Listen for onload, and remove the script after execution
    s.addEventListener("load", function(e) {
        s.parentElement.removeChild(s);
    });

    // Load the code inside the script and run it in the head
    s.textContent = xhr.responseText;
    document.head.appendChild(s);
})();

Now your custom.js script will (anonymously) run before DOMContentLoaded , mission complete! 现在你的custom.js脚本将(匿名)在DOMContentLoaded之前运行,任务完成!

As far as I can see, there are multiple ways of doing this, but the best way would be to use something like Require.js or CommonJS to resolve your dependencies, concat them, and and publish the resulting concatenated javascript file (or many if you can divide your app into multiple sections). 据我所知,有多种方法可以做到这一点,但最好的方法是使用诸如Require.js或CommonJS之类的东西来解析你的依赖关系,连接它们,并发布生成的连接的javascript文件(或许多if您可以将您的应用划分为多个部分)。

The not-so-great method would be to use the main script to load other scripts by adding script tags, this way you can ensure its there since its the one loading the other scripts. 不太好的方法是使用主脚本通过添加脚本标记来加载其他脚本,这样就可以确保它在那里加载其他脚本。

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

相关问题 如何使用 React Native 和 AWS 确保每次都导入我的个人资料信息? - How do I make sure my Profile information is imported every time, using React Native and AWS? 在调用另一个函数之前,请确保已加载JS文件并调用了JS函数 - Make sure JS file is loaded and JS function is called BEFORE calling another function 在提交表单之前,如何确保重新验证码js文件已加载? - How to make sure that the re-captcha js file has been loaded before submitting a form? 如何确保API调用在React中加载另一个页面之前完成 - How to make sure API calls completes before another page loads in React 如何确保 ajax/jquery 调用在 html 页面加载之前完成? - How can I make sure ajax/jquery calls finish before an html page loads? 为什么每次页面加载时我的脚本都不会运行? - Why won't my script run every time the page loads? 如何确保在页面加载之前显示背景图像? - How can I make sure a background image displays before the page loads? jQuery确保一种功能先于所有其他功能运行的最佳方法 - jQuery best way to make sure one function is run before all others 如何优化我的代码以确保它锁定每个单元格? - How to optimize my code to make sure it locks every cells? 如何确保部分加载JS文件一次? - How to make sure I load the JS file just once in my partial?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM