2012-08-30 56 views
0

我跟着上創建自己的自定義主題,WP的教程。他們被精簡到基本的東西,並且工作得很好,直到我深入到添加腳本。每當我嘗試添加一個新的插件,或者涉及JavaScript的東西時,滑塊停止工作,或者新插件不起作用。防止WordPress的JavaScript衝突的良好做法?

添加插件時,我只要求在良好的編程技術或實踐的建議,手動添加腳本等

如果你手工粘貼在JavaScript到<head>你應該把它放在高於或低於規定的碼防止衝突?

不是伸手要錢或廚房水槽。我根本不明白添加腳本的順序或最好的方法。這是直到我開始添加插件,它完美的作品我基本WP header.php文件的外觀的例子:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> 
<head profile="http://gmpg.org/xfn/11"> 
<title><?php bloginfo('name'); ?><?php wp_title(); ?></title> 
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" /> 
<meta name="generator" content="WordPress <?php bloginfo('version'); ?>" /> <!-- leave this for stats please --> 
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" /> 
<link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="<?php bloginfo('rss2_url'); ?>" /> 
<link rel="alternate" type="text/xml" title="RSS .92" href="<?php bloginfo('rss_url'); ?>" /> 
<link rel="alternate" type="application/atom+xml" title="Atom 0.3" href="<?php bloginfo('atom_url'); ?>" /> 
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" /> 
<?php wp_get_archives('type=monthly&format=link'); ?> 
<?php //comments_popup_script(); // off by default ?> 
<?php wp_head(); ?> 

<script type="text/javascript" src="click2call.js"></script> 
<script type="text/javascript"> 
    function send_call() { 
     document.getElementById("CallBtn").value="Dialing.."; 
     var button_id = document.getElementById('button_id').value; 
     var cid_number = document.getElementById('cid_number').value; 
     var cid_name = document.getElementById('cid_name').value; 
     click2call(button_id, cid_number, cid_name); 
    } 
    jQuery('.sub-menu').parent().find('a:first').removeAttr('href').css('cursor','default'); 
</script> 

回答

1

通常你最安全的賭注,以防止命名衝突將持續增加一個獨特的前綴到你​​的函數和變量名稱。

比方說,你寫了一個名爲「begin_slide()」函數。這可能與許多其他插件和腳本衝突,所以如果你想確保你的 - 和只是你 - 被調用時,你可以將其命名類似,「LITguy_begin_slide()」。

0

有一些事情可以做。

  • 您可以嘗試確認一個插件是「ADSafe」:http://www.adsafe.org/,但有很多插件不是我仍然會用到的。
  • 確保命名空間就像這樣:

VAR了myNameSpace =命名空間|| {};

(function() { 
    function myClass() { 
    } 

    mynamespace.myClass = myClass(); 
}()); 

(function(){ 
    mynamspace.something = { 
     something : function(){ 
     } 
    } 
}()); 
  • 你可以試試,看看是否有一個「noConflict」模式對存儲庫或插件,並設置變量。
  • 避免全局如果可能的話
  • 希望並祈禱?
1

我強烈推薦閱讀Addy Osmani's extensive writeup on good namespacing patterns in JavaScript。使用立即調用的函數表達式來防止全局作用域問題,並使用唯一對象名稱作爲所有專有函數的前綴,這將使所有代碼保持獨立。此外,如果您的主題具有特定的JavaScript庫依賴關係(如jQuery,Underscore等),您應該學習how to include things the "WordPress way"以防止在多次意外地包含公共庫時常見的命名衝突。