Мы уже разбирали как добавить к себе в приложение стороннюю JS библиотеку moment.js. Но там мы грузили JS файл локально. Что делать, если надо добавить библиотеку не со своего, а стороннего сервера?
Подгрузим CSS со стороннего сервера:
jQuery.sap.includeStyleSheet("//nickcode.ru/css/style.css"); |
где nickcode.ru/css/style.css - путь до CSS файла на стороннем сервере.
Можно воспользоваться аналогичным методом для JS файлов:
jQuery.sap.includeScript({ url: "//nickcode.ru/js/script.js", id: "scriptId" }).then(function() { console.log("Script has been loaded!") }) |
где nickcode.ru/js/script.js - путь до JS файла на стороннем сервере.
Может возникнуть задача передать какие-либо параметры JS скрипту.
Например, вызов скрипта должен выглядеть следующим образом:
<script data-host="http://nickcode.ru" data-id="1234567890" data-style="default" src="//nickcode.ru/js/script.js" id="scriptId"></script> |
Помимо id и пути до JS файла надо предать еще параметры: data-host, data-id, data-style. К сожалению, метод includeScript не поддерживает дополнительных параметров.
Для решения этой задачи погрузимся в исходный код метода includeScript:
var oScript = window.document.createElement("script"); oScript.src = sUrl; oScript.type = "text/javascript"; if (sId) { oScript.id = sId; } |
Чуть преобразуем код для нашего случая, в итоге вызов удаленного JS скрипта с параметрами будет выглядеть следующим образом:
var head = window.document.getElementsByTagName("head")[0]; var oScript = window.document.createElement("script"); oScript.src = "//nickcode.ru/js/script.js"; oScript.type = "text/javascript"; oScript.id = "scriptId"; oScript.setAttribute("data-host", "http://nickcode.ru"); oScript.setAttribute("data-id", "1234567890"); oScript.setAttribute("data-style", "default"); //Добавим в head if (head){ head.appendChild(oScript); } |
Если мы зайдем в документацию по jQuery.sap.includeScript —
https://openui5.hana.ondemand.com/api/jQuery.sap#methods/jQuery.sap.includeScript, то узнаем, что метод уже устарел. Рекомендуют использовать sap/ui/dom/includeScript.
Посмотрим в исходный код нового метода и увидим, что поддержка параметров уже реализована в sap/ui/dom/includeScript:
* @param {object} [vUrl.attributes] map of attributes that should be used for the script tag |
Воспользуемся этим и переделаем подгрузку CSS и JS следующим образом:
sap.ui.define([ "sap/ui/core/Component", "sap/ui/dom/includeScript", "sap/ui/dom/includeStylesheet" ], function(Component, includeScript, includeStylesheet) { return Component.extend("nickcode.Component", { metadata: { "manifest": "json" }, init: function() { //Загрузим CSS includeStylesheet("//nickcode.ru/css/style.css"); //Подготовим объект для JS var oScript = {}; oScript.url = "//nickcode.ru/js/script.js"; oScript.attributes = {}; oScript.attributes["data-host"] = "http://nickcode.ru"; oScript.attributes["data-id"] = "1234567890"; oScript.attributes["data-style"] = "default"; //Загрузим JS includeScript(oScript, "scriptId").then(function(){ console.log("Script has been loaded!"); }); } }); }); |
Ну как Вам, не правда ли так более красиво выглядит загрузка JS библиотек с внешних серверов? :)
А теперь самое интересное! В конце заметки посмотрим на еще один интересный метод, при помощи которого можно подгрузить стороннюю JS библиотеку в свой SapUI5 проект.
И о чудо, она по умолчанию используется в SapUI5.
Давайте при помощи RequireJS загрузим библиотеку для работы с датами date-fns.org с cdnjs.
Для этого я накидал небольшой примерчик, который вы можете импортировать в свой WebIDE отсюда https://github.com/kannade/sapui5_external_js.
Посмотрим как это можно сделать:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /* global requirejs:true */ sap.ui.define([ "sap/ui/core/mvc/Controller", "sap/ui/thirdparty/require"], function (Controller) { "use strict"; return Controller.extend("nickcode_ru_external_js.controller.View1", { onInit: function () { var oLabel = this.getView().byId("labelId"); var oPromise = new Promise(function (resolve, reject) { requirejs.config({ paths: { "date_fns": ["//cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.min.js"] } }); resolve(); }); oPromise.then(require(["date_fns"], function (oDateFns) { oLabel.setText(oDateFns.parse("03.06.2020", "dd.MM.yyyy", new Date())); })); } }); }); |
На этом, пожалуй, все. Уверен, что существуют еще и другие методы, при помощи которых можно подгрузить JS библиотеку в свой проект. Жду их от вас в комментариях :).
turkce izle
Man kann jeden Tag etwas Neues hier lernen. Ich bin ein regelmäßiger für die meisten von denen Blogs, aber immer noch nicht um ein Paar von ihnen wissen.
Legra Christophorus Dumas
Val la pena llegir-lo el vostre article. Legra Christophorus Dumas
Ilysa Carolus Spragens
excelente artigo. Ilysa Carolus Spragens
Matti Correy Kosaka
You do have a fabulous blog thanks. Matti Correy Kosaka
Fredelia Chance Margalit
Völlig komponiertes Themenmaterial, danke für die selektive Information. Fredelia Chance Margalit
Ninon Nial Sloatman
Ich habe hier einige ausgezeichnete Sachen gelesen. Auf jeden Fall Preis Lesezeichen für einen erneuten Besuch. Ich frage mich, wie viele Versuche Sie unternehmen, um eine so hervorragende informative Website zu erstellen. Ninon Nial Sloatman
Mignon Fowler Judie
Bonjour, toujours super de voir d’autres personnes à travers le monde du trou dans ma recherche, j’apprécie vraiment le temps qu’il aurait fallu pour créer cet article génial. À votre santé Mignon Fowler Judie
erotik izle
hola me encanta la cabecera de tu blog, es una creación personal? Penny Reggis Laurentia
erotik
Puedo encontrar buena información de este artículo. Grazia Roderick Buonomo
No purchase necessary
Ich habe es genossen, Ihren Artikel zu lesen.
Ayn Sanson Dwan
Ashil Chic Chaffee
Hola y gracias por este blog es una verdadera inspiración .. Ashil Chic Chaffee
Serious only
Hallo, always great to see other people through the hole world in my searching, I really appreciate the time it should have taken to put together this awesome article. Cheers
Klarrisa Oliviero Maryanna
iphone
I really believe you will do well in the future I appreciate everything you have added to my knowledge base. Jemmie Benjy Lavelle
Google
The time to study or stop by the content or web sites we’ve linked to below.
Google
Here is an excellent Blog You may Come across Interesting that we encourage you to visit.
porno
If you want to use the photo it would also be good to check with the artist beforehand in case it is subject to copyright. Best wishes. Aaren Reggis Sela
erotik izle
If you want to use the photo it would also be good to check with the artist beforehand in case it is subject to copyright. Best wishes. Aaren Reggis Sela
erotik izle
Hello. This article was really motivating, especially since I was browsing for thoughts on this subject last Sunday. Dawn Pacorro Sabina
erotik izle
If you want to take a good deal from this article then you have to apply such strategies to your won webpage. Cathe Moritz Calvo
porno
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
porno
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
porno
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
porno
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
porno
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
porno izle
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
porno
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
porno child
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
reed dwight
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
fredrick molla
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
evelia abner
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
vanetta uribazo
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
cheri sedar
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
stephine romaine
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
nestor insley
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
theola nucci
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
alline berky
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
eddie posthuma
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
erna pelot
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
melodie martig
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
rupert apodace
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
donovan super
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
noah colgate
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
joseph nicolaus
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
joseph nicolaus
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
clay biros
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
erotik
Way cool! Some very valid points! I appreciate you writing this post plus the rest of the website is really good. Codi Fax Eveleen
sikis izle
I cannot thank you enough for the article. Really looking forward to read more. Want more. Jayne Jean Marr
erotik
Great post! We will be linking to this particularly great post on our site. Keep up the good writing. Megen Biron Bollinger
erotik izle
When some one searches for his essential thing, thus he/she wants to be available that in detail, so that thing is maintained over here. Cindee Haywood Monjo
sikis izle
Article writing is also a fun, if you be acquainted with afterward you can write or else it is complex to write. Maridel Rowan Fredek
erotik film izle
Thanks for the blog article. Really thank you! Want more. Dinah Mickey Oakleil
evelia abner
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
erotik
Enjoyed examining this, very good stuff, thanks . Kippy Grantley Suzanna
erotik
Helloo Dear, are you in fact visiting this site daily, if so then you will without doubt obtain fastidious experience. Nettie West Geralda
garret marcille
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
kimberli sens
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
neil vandawalker
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
elijah graniero
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
ronda tote
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
sammy minter
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
merle politowski
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
frederick marsala
You made some nice points there. I looked on the internet for the subject matter and found most individuals will agree with your site.
waldo batimon
Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!
website
Your post content is being interested by a lot of people, I am very impressed with your post. I hope to receive more good articles.
a
Hi! If you need to produce case brief for tomorrow, don’t worry and write guys on this website. Believe me, they will make a perfect work.
video
Hello. In my opinion you are mistaken. I can prove it.
کلیک کنید
hello
آهنگ
Thanks for a marvelous posting! I quite enjoyed reading it, you’re a great author.
site
It’s great to be here with everyone, I have a lot of knowledge from what you share, to say thanks, the information and knowledge here helps me a lot.
altyazili
Everything is very open with a precise description of the issues. It was truly informative. Your website is very helpful. Many thanks for sharing! Merci Dimitri David
bollywood
I must convey my affection for your generosity giving support to folks that really need guidance on this idea. Your real dedication to getting the message all through has been unbelievably advantageous and has frequently permitted associates much like me to arrive at their ambitions. Your helpful tutorial denotes a lot a person like me and even further to my office colleagues. Thank you; from each one of us. Gloriana Arvy Lundeen
Google
Although sites we backlink to beneath are considerably not connected to ours, we really feel they’re actually really worth a go by, so have a look.
online
Great travelogue. Beautiful pictures. Brought back many memories as I grew up in Washington. Camped on mt. Rainer, st Helens as a kid. Puget sound wonderful body of water. Take a ferry ride next time. Walk on riders travel free. Jania Granger Allistir
Virgie
I am truly delighted to read this weblog posts which includes tons of helpful facts, thanks
for providing these information.
This is nicely put! !
Thanks a lot, A good amount of advice!
Thank you. Awesome stuff!
How long do I have to use this product before I see results?
Remember, it’s critical to give Lean Belly 3X an honest chance to work by taking it as recommended for at least 60 days.
Like all Beyond 40 products, Lean Belly 3X is made with the highest quality ingredients, but
no product will work miracles overnight.
Feel free to surf to my page … Lean belly 3x supplement side
effects