【问题标题】:shopify scriptTag - how to add css file dynamically?shopify scriptTag - 如何动态添加css文件?
【发布时间】:2018-02-24 18:07:06
【问题描述】:

我想为商家添加一个选项,以自动将我们的 sn-p 包含在他们的产品和购物车页面中。

为此,我们计划使用插入 html 的 scriptTag 来显示 sn-p。

我的问题:

  1. 是否可以在我们的代码运行时加载自定义 css 文件?
  2. 如何判断代码是否在产品页面或购物车页面上运行?

感谢您的帮助

【问题讨论】:

  • 因为您在脚本中内联 HTML,所以也内联您的 css。
  • @DavidLazar,是的,但这在使用外部库时很难。

标签: shopify shopify-app


【解决方案1】:

您可以使用以下选项加载 JS/CSS

1) 选项 1:自定义现有的活动主题 .liquid 模板。并在 footer.liquid 中注入您的 JS 文件,其中包含所有代码 (THIS IS NOT RECOMMENDED WAY)

function loadjscssfile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

2) 选项 2:创建您自己的 PRIVATE SHOPIFY APP 并使用脚本标签插入您自己的 JAVASCRIPT FILE 当店主卸载您的私人应用程序时然后自动您插入的代码也将被删除 (THIS IS RECOMMENDED WAY)

参考:https://help.shopify.com/api/reference/online_store/scripttag


问题:如何知道当前在哪个页面?通过使用 ScriptTag 插入 JAVA-SCRIPT ?

答案:使用以下代码示例进行 shopify 页面识别

$(document).ready(function() {

     if (window.location.href.indexOf("product") > -1) {

         // Console.log("We're in product detail page");

     }else if(window.location.href.indexOf("cart") > -1){

         // Console.log("We're in cart page");

     }

}); 

【讨论】:

  • 或者您可以进一步简化,只需使用保护语句:if (window.location.href.indexOf("product") === -1) return; 和下面的其余代码
猜你喜欢
  • 1970-01-01
  • 2012-08-19
  • 2012-07-27
  • 1970-01-01
  • 2019-03-16
  • 2016-09-27
  • 2019-11-06
  • 2011-01-07
  • 2011-02-08
相关资源
最近更新 更多