简体   繁体   English

动态加载javascript文件时的延迟函数调用

[英]Delay function call when dynamically loading javascript files

I am using enquire to dynamically load javascript files but hitting what I can only assume to be a loading priority problem since it works some of the time. 我正在使用查询动态加载javascript文件但是我只能假设是加载优先级问题,因为它在某些时候有效。 Is there a way to hold off running a function until all files are loaded? 有没有办法阻止运行函数,直到加载所有文件?

The relevent bit of enquire is 相关的问题是

enquire.register("screen and (min-width: 564px)", {
    match : function() {
    loadJS('script/jquery.js');
    loadJS('script/jquery.slides.min.js');
    loadJS('script/TMSScript.js');
    }

and the load function is 并且加载功能是

function loadJS(url)
{
    var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.head.appendChild(script);
}

The function I need to run is located at the end of TMSScript.js and it calls the jquery plugin so all 3 files need to be loaded in order for it to work. 我需要运行的函数位于TMSScript.js的末尾,它调用jquery插件,因此需要加载所有3个文件才能使它工作。 If I load all files in the header then the function will execute fine with a simple onload call in the body. 如果我加载标题中的所有文件,那么函数将在正文中通过简单的onload调用执行。

The idea is that a different method will be used on mobiles for my gallery (probably jquery mobile) and I don't want to load any unnecessary files. 我的想法是在我的图库(可能是jquery mobile)的移动设备上使用不同的方法,我不想加载任何不必要的文件。

Someone may correct me, but I believe outside of either loading these three in separate script tags placed in the correct order, or loading a single js file with these plugins concatenated in the correct order, you can't. 有人可能会纠正我,但我相信除了将这三个加载到以正确顺序放置的单独脚本标记中,或者加载单个js文件时,这些插件以正确的顺序连接,你不能。 Loading a src on a programatically created element now runs in an async fashion (in current browsers anyways I beleive), meaning you wouldn't be sure exactly when it's going to return back, and in what order. 在编程创建的元素上加载src现在以异步方式运行(在当前的浏览器中反正我相信),这意味着你不确定它何时返回,以及以什么顺序返回。

It sounds like you want to use something like browserify or require.js which can help handle what you're trying to accomplish. 听起来你想使用像browserify或require.js这样的东西来帮助处理你想要完成的事情。 I suggest checking out those projects. 我建议查看那些项目。

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

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