2013-10-06 58 views
0

我正在從themeforest實現這個Developr theme到Meteor應用程序。如何等待DOM加載之前,將腳本標記添加到<head>?

我目前通過把有問題的JavaScript的以/public並使用它們附加jQuery的完成這樣的:

Meteor.startup(function() { 
    $('head').append('<script src="/template_stuff.js"></script>'); 
    // .. all 7 scripts or so 
}); 

如果需要的腳本放置在/client/js/,看來,他們要麼運行太早或之前DOM完成加載。如果將它們直接放置在主html文件的標題中,它們似乎以同樣的方式出錯。

我在這裏丟失了一些東西 - 是否有一個更優雅的方式來使DOM加載後加載腳本?

+0

爲什麼不使用jQuery'$ .getScript()'http://api.jquery.com/jQuery.getScript/ – Daniel

+0

你並不需要將它們添加到頭部如果你正在等待DOM加載。 – RedGlobe

回答

1

有等待,直到DOM加載注入腳本幾種方法:

  • Meteor.startup(如你所示)
  • jQuery的文件準備:$(function() { ... })
  • 腳本標籤在底部你的佈局模板

關於優雅,我使用了一個把手幫手,因爲它允許我在一個地方合併所有'身體後的代碼。然後根據需要使用jQuery的文檔。

例如,

// in client/handlebars.js 

Handlebars.registerHelper('afterBody', function(name, options) { 

    function isMobileSafari() { 
    return navigator.userAgent.match(/(iPod|iPhone|iPad)/) && 
      navigator.userAgent.match(/AppleWebKit/) 
    } 

    if (isMobileSafari()) { 
    $(function() { 
     FastClick.attach(document.body) 
    }) 
    } 

    //// load scripts however you want... 
    // $(function() { 
    // $.getScript as Daniel suggests 
    // $('body').append as you have 
    // pure js: document.createElement('script') 
    // }) 

}) 


// in client/main.html (using mini-pages router) 

<template name="layout_no_header"> 
    {{{yield}}} 

    {{afterBody}} 
</template> 

<template name="layout"> 
    {{> header}} 

    {{{yield}}} 

    {{afterBody}} 
</template> 
0

使用jQuery getScript加入()

(function ($) { 
    $.getScript("/template_stuff.js"); 
})(jQuery); 
0

我想你可能有一個不同的問題。這聽起來像是第三方代碼被封裝在閉包中,並且無法正常工作。嘗試將它們放入client/compatibility文件夾中。這將防止它被包裹在關閉中,這可以解決第三方問題。確保這裏面的加載順序是正確的,它在文件夾內按字母順序加載文件。 (load order

如果這樣不起作用,請找出正在執行代碼的位置並註釋掉該呼叫。然後在模板中加載你的html,即使它只是一個包含所有html的'頁面'模板。爲模板創建一個js文件,並調用模板呈現回調中的方法。

// Execute this function when myPage template is rendered 
Template.myPage.rendered = function() { 
    stuff.init(); 
    stuff2.run(); 
}; 

注意,在調用stuff2,等等。你可能需要把它的劇本在兼容性文件夾,這樣你就可以從template_stuff.js達到的命名空間。

相關問題