gpt4 book ai didi

javascript - 如何识别加载了一个js文件?

转载 作者:行者123 更新时间:2023-11-28 15:12:50 25 4
gpt4 key购买 nike

我尝试在页面加载时显示进度条。我想在加载 js 文件后更改进度条的宽度。最后加载所有文档后,进度条设置为 100%。现在我需要识别使用 javascript 加载的 js 文件。这可能吗 ?请指教。

最佳答案

对于内部js文件加载识别:

由于可以从另一个文件访问函数和变量,因此您可以设置全局进度变量的值并通过调用函数显示其值

//on page or head js file
var progress = 0;

function displayProgress()
{
//show progress based on 'progress' variable
}
//file1.js
progress += 10;
displayProgress();
...
//file2.js
progress += 20;
displayProgress();
...

对于外部js文件,有很好的article 。主要思想是定期检查外部函数是否存在(typeof fixpng =='function'),如果存在 - 停止检查并显示进度。

Here's the JavaScript code to load the external library with a callback passed in:

 function loadExtScript(src, callback) {   var s =   document.createElement('script');   s.src = src; document.body.appendChild(s); // if loaded...call the callback }

Firefox allows you to listen for the onload event on the script element:

s.onload = callback;

With Internet Explorer you can wait for a state change on the script element:

s.onreadystatechange = function() { if ( this.readyState != "loaded"
) return; callback.call(); }

The problem comes with Safari - there's no event change for Safari, so we can't tell when the script has loaded. This is the solution I came up with (and this solution should also work with Opera):

function loadExtScript(src, test, callback) {   var s = 

document.createElement('script'); s.src = src;
document.body.appendChild(s);


var callbackTimer = setInterval(function() {
var call = false;
try {
call = test.call();
} catch (e) {}

if (call) {
clearInterval(callbackTimer);
callback.call();
} }, 100); }

The function takes a test as a parameter. Since you are the designer of the app, you'll know what successful test is. Once this test is true, it will execute the callback. A simple test could be to check whether a function exists, for example:

loadExtScript('/fixpng.js', function() {   return (typeof fixpng ==
'function'); }, myCallbackFunction);

关于javascript - 如何识别加载了一个js文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35501174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com