简体   繁体   English

将外部JS添加到Magento 2

[英]Add external JS to Magento 2

I'm a front-end developer and don't have any access to Magento 2 admin panel.我是一名前端开发人员,无权访问 Magento 2 管理面板。 I've created a custom plugin I would like to use and currently I'm adding external scripts to the plugin in the following way (works on every platform I tested except Magento 2) -我创建了一个我想使用的自定义插件,目前我正在通过以下方式将外部脚本添加到插件中(适用于我测试的每个平台,除了 Magento 2) -

var cropperScript = document.createElement('script');
cropperScript.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.2.1/cropper.min.js');
document.head.appendChild(cropperScript);
var loadImageScript = document.createElement('script');
loadImageScript.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/blueimp-load-image/2.19.0/load-image.all.min.js');
document.head.appendChild(loadImageScript);

However, in all the Magento 2 sites I've tested the external scripts appear in the sources tab but they are undefined.但是,在我测试过的所有 Magento 2 站点中,外部脚本出现在源选项卡中,但它们未定义。

Any help would be appreciated!任何帮助,将不胜感激! Thanks in advance提前致谢

if you can don't use external script, download it and:如果您不能使用外部脚本,请下载它并:

1 - In your Theme Folder: 1 - 在您的主题文件夹中:

put the script.js in将 script.js 放入

app/design/frontend/theme/MyTheme/web/js/

2 - Create a layout to add your script 2 - 创建一个布局来添加你的脚本

app/design/frontend/theme/MyTheme/Magento_Theme/layout应用程序/设计/前端/主题/MyTheme/Magento_Theme/layout

Create default.xml and add:创建 default.xml 并添加:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="js/myscript.js"/>
    </head>
</page>

If you really need to be an external link do this in the layout:如果您确实需要成为外部链接,请在布局中执行此操作:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.2.1/cropper.min.js" src_type="url"/>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-load-image/2.19.0/load-image.all.min.js" src_type="url"/>

    </head>
</page>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM