在CSS完全加载后运行Javascript

Running Javascript after CSS is fully loaded

本文关键字:运行 Javascript 加载 CSS      更新时间:2024-05-25

我有一些代码取决于加载的css
我在页眉上加载css,然后在页脚上加载javascript

我用$(document).ready 尝试了javascript


$(document).ready(function() {
  var bar_position, width;
  bar_position = $('body').height() - 38;
  width = $('body').width();
  console.log(bar_position);
  if (width <= 480) {
    console.log("Entered");
    $('#accounts-bar').css("top", bar_position);
  }
});

我试过$(window).ready$(window).load,但都失败了。

您的代码真的很糟糕(除非您使用的是CoffeeScript)

$(function () {
    bar_position = $('body').height() - 38; //38 is the size of the bar 
    width = $('body').width();
    console.log(bar_position);
    if (width <= 480) { //480 is the mobile width
        console.log("Entered");
        $('#accounts-bar').css("top", bar_position);
    }
});

CSS被加载在页眉中,JS被加载在页脚中,并被包装在文档中,在JS代码执行之前,你应该可以应用CSS。我猜元素没有宽度的原因是它是display: none;,或者只包含浮动元素,或者类似的东西。换句话说,我认为这是一个CSS问题,而不是JS时间问题。试着进入你的Firebug/Chrome控制台,选择有问题的元素,并获取其宽度。

JavaScript注释不是#,而是//

错误

bar_position = $('body').height() - 38 #38 is the size of the bar

右侧

bar_position = $('body').height() - 38 //38 is the size of the bar

还有一堆其他错误,代码无法运行。猜测您错过了一个标记,这不是纯JavaScript,因为它是块范围缩进的,到处都缺少大括号/闭包。

就绪事件就足够了。

当使用依赖于CSS样式属性值的脚本时,引用外部样式表或嵌入样式很重要元素,然后再引用脚本。

在代码依赖于加载的资产的情况下(例如,如果图像的尺寸是必需的),代码应该放在加载事件的处理程序。

此外,您的javascript无效。如果它应该是CoffeeScript,则您缺少->:

$(document).ready ->
  bar_position = $('body').height() - 38 #38 is the size of the bar 
  width = $('body').width() 
  console.log(bar_position)
  if (width <= 480) #480 is the mobile width
    console.log("Entered");
    $('#accounts-bar').css("top", bar_position)
  return 

如果它应该是JavaScript,那么您会遇到更多问题:

$(document).ready(function(){
    bar_position = $('body').height() - 38; //38 is the size of the bar 
    width = $('body').width(); 
    console.log(bar_position);
    if (width <= 480) //480 is the mobile width {
      console.log("Entered");
      $('#accounts-bar').css("top", bar_position);
    }
});
$(window).bind("load", function() {
   // code here
});