Cordova:在加载html元素之前加载Javascript

时间:2016-06-14 22:20:16

标签: javascript cordova

我是bootstrap datepicker。现在我想通过javascript启动一个datepicker事件。我要应用datepicker的html元素如下所示,并在index.html中定义。

<input type="text" placeholder="Departure date..." data-provide="datepicker" class="calendar-box">

这里是main.js文件中定义的javascript代码。

$('.calendar-box').on('changeDate', function(ev){
    $(this).datepicker('hide');
});

当我调试这段代码并尝试查找$('.calendar-box')时,它给了我一个空数组,这意味着html元素没有在这段代码运行时定义。

这是加载脚本的顺序。

    <script type="text/javascript" src="libs/jquery.js"></script>
    <script type="text/javascript" src="libs/bootstrap-datepicker.min.js"></script>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="libs/index.js"></script>
    <script type="text/javascript" src="libs/platformOverrides.js"></script>
    <script type="text/javascript" src="libs/angular.min.js"></script>
    <script type="text/javascript" src="libs/angular-route.min.js"></script>
    <script type="text/javascript" src="scripts/assets.js"></script>
    <script type="text/javascript" src="scripts/assets.js"></script>
    <script type="text/javascript" src="scripts/main.js"></script>

问题是如何运行脚本,以便$(&#39; .calendar-box&#39;)为我提供正确的标记。我已经尝试将javascript代码放在deviceReady事件和document.ready下。但仍然可以为calendar-box获得一个emptry数组。

如果您需要了解其他内容,请告诉我。

1 个答案:

答案 0 :(得分:0)

如果您不关心阻止,请将脚本放在document.write

        document.write('<script type="text/javascript" src="scripts/assets.js"><' + '\/script>');

如果你关心,你可以使用像requireJS这样的东西,或者像穷人的装载机之类的东西,称之为异步(不要被更好的东西混淆)

 /**
  * Async accepts a url and a callback, it loads the script, adding an eventListener
  * to make sure the callback is done when the script is loaded
  * @param {String} some url
  * @param {onLoadCallback} you do whatever you want when this callback is called
  **/
  var loadAsyncScript = function(url, onLoadCallback) {
    var script = document.createElement('script');
    var parent = document.getElementsByTagName('script')[0];

   if (onLoadCallback) {
     // assign event before src is set,
     // IE may start getting scripts just after src is assigned and before script is attached to DOM
     attachEvent(script, 'load', onLoadCallback);
   }

   script.async = true;
   script.src = '//' + url;
   parent.parentNode.insertBefore(script, parent);
};