Link external pure javascript file to my React component - javascript

I am trying to build a react component with happy birthday animation written in an external javascript file. I know that we could link external javascript file by:
componentDidMount() {
const script = document.createElement("script");
script.async = true;
script.src = "./hbd.js";
script.type = "text/javascript";
this.div.appendChild(script);
}
In the hbd.js javascript file I have a function anim() which I could call to display an animation.
However, if I don't change the type of script to script.type = "text/bable " or script.type = "text/jsx " it gives me an Uncaught SyntaxError: Unexpected token '<'
error. If I do change the types, no error is given but the file simply won't load, and no animation effect is seen.
Does someone out there know if it is possible at all to do that with React?

Make sure that you can GET the JavaScript file hbd.js. Point your browser to the full url and make sure that the hbd.js file is returned by the web server. If you have your web server locally, it would be something like http://localhost/hbd.js.

Related

Could not include javascript file dynamically using angular4 and Javascript

I am unable to include one javascript file dynamically inside angular4 submit method. I am explaining my code below.
onTextFormSubmit(){
this.processValidation = true;
if (this.textForm.invalid) {
return;
}
let urlValue = this.textForm.value;
let url = urlValue.url;
console.log('hello',url);
var script = document.createElement("SCRIPT");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", url);
script.setAttribute('integrity', 'sha384-tEgmOghGBnPJQ3h63qzTE8V69SDVkIIyQeOFDfsG+AWJqA/UfZMmyQcXQVunl3wT');
script.setAttribute('crossorigin','anonymous');
document.getElementsByTagName("head")[0].appendChild(script);
}
Here the url parameter is coming from form submit which is like https://code.jquery.com/jquery-2.2.4.min.js this and I am including it dynamically but after submit when I am doing view page source and searching that file isnide the head tag, I did not found there which is my issue. I need to include this file dynamically.
Iv'e tested it in my environment and it also failed.
Iv'e got the following error:
Failed to find a valid digest in the 'integrity' attribute for
resource 'https://code.jquery.com/jquery-2.2.4.min.js' with computed
SHA-256 integrity 'BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44='. The
resource has been blocked.
After a little search I found this git issue that resolved it.
Simply add the following attribute to your script:
script.setAttribute('integrity','');
Edit:
If it's still doesn't work try this :
script.setAttribute('integrity','sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=');
script.setAttribute('crossorigin','anonymous');

Adding a javascript line to a ruby site written in slim

I was given a javascript line that calls a javascript file which is made by a company called walkme.
I have an app/assets/javascript/application.js file that calls all of my jquery that I am using for the site. for example it contains:
require feed
which calls feed.js when someone is on the feed page. I would like the walkme.js to also be called at the same time this code is called
I am looking for a way to add this <script ... code to a ruby site that uses slim and jquery.
<script type="text/javascript">(function() {var walkme = document.createElement('script'); walkme.type = 'text/javascript'; walkme.async = true; walkme.src = 'https://cdn.walkme.com/thewalkme.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(walkme, s); window._walkmeConfig = {smartLoad:true}; })();</script>
I have tried a blunt style of just making a walkme.js in the same place as the feed.js and putting that <script ... code in that file while adding the necessary require walkme code, but that seems to do nothing.
Some info:
Ruby on Rails
Ruby 2.1.7p400
ubuntu 14.04 LTS server
some files are named *.html.slim
As you may be able to tell, I did not make all the ruby code and am not an expert in ruby, javascript or jquery.
If this was just an html site, I think could just add the line of code to the header.
Mostly, Javascripts are called after the page has finished loading, since you want to manipulate the DOM, most likely.
So, you either don't want to call the script in the head of your document, unless you have a document.ready in the script.
To answer your question then, if you want the following script:
function(){
var walkme = document.createElement('script');
walkme.type = 'text/javascript';
walkme.async = true;
walkme.src = 'https://cdn.walkme.com/thewalkme.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(walkme, s);
window._walkmeConfig = {smartLoad:true};
};
to be available only on the feed page of your application,
You can make this function a named function, in a separate file (say feed.js.coffee for example) and call the function in your slim view page as follow:
//feed.js.coffee:
#feed = ->
walkme = document.createElement('script')
walkme.type = 'text/javascript'
walkme.async = true
walkme.src = 'https://cdn.walkme.com/thewalkme.js'
s = document.getElementsByTagName('script')[0]
s.parentNode.insertBefore walkme, s
window._walkmeConfig = smartLoad: true
return
and in your view:
/feed.html.slim:
...
your codes...
...
coffeeview:
feed

Adding external Javascript file based on url string

I am attempting to load an external JS file to the end of the body if the URL does not container a given parameter. Here is what I have tried without any success. I am looking to load the file if the URL does not contain ?A=Edit
if (/[?]A=Edit/.test(window.location.href)) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/js/inner-functions.js';
$('body').append(script);
}
If anyone can point me in the right direction that would be great.
Just inverse your condition:
if (!/[?]A=Edit/.test(window.location.href)) {
...
You should verify your application context/state inside your .js file, not outside.

problems when creating a script tag to a local file in android webview

I have an Android application that consist in a simple WebView that load a local html file in the assets folder of the project.
The HTML has a tag that calls (AJAX) an external service and expects as a response a String that represent a .js filename (say, 'test.js').
In test.js there is a simple funcion declaration, as:
var testFunction = function(){
// some code here
}
The AJAX callback then construct via javascript a tag that points to the .js file and append it to the head of the document; then call the testFunction:
$.ajax('externalService').done(function(response){
var script = // construct the script tag;
$('head').append(script);
testFunction();
});
Important: the script tag points to an external .js file, like
<script src="http://justatest.com/test.js">
... and all works fine!
Now i try to do the same thing putting the test.js inside the assets folder of the project. Obviously i changed the src of the script created in the callback with a relative path:
<script src="test.js"></script>
but when i try to invoke the function testFunction i get an error (testFunction is not defined).
The local path is correct (i put jquery.js in the same local folder of test.js and loaded it directly in the html with a with no errors).
I put all the attributes (like type="text/javascript") in the tag as well...
so, why the webview doesn't load a local .js file in this way?
thank you :)
EDIT: I tried the solution found in this thread:
jQuery getScript not working in Android WebView when using Local Assets/HTML/Resources
and it worked!!!!
I tried the solution found in this thread:
jQuery getScript not working in Android WebView when using Local Assets/HTML/Resources
and it worked!
I report the solution:
var scriptUrl = "test.js";
var head = document.getElementsByTagName("head")[0];
script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptUrl;
script.onload = function() { alert("Success"); };
script.onerror = function(e) { alert("failed: " + JSON.stringify(e)); };
head.appendChild(script);
So if i use the jquery append() method it doesn't work, but if i use the javascript appendChild method it work...

Can I Load CSS Using the "load.js" Library?

I recently found out about load.js, but I can't seem to find any indication of whether or not this is possible... (Note: I can't find a 'load.js' tag..)
I've got load.js successfully loading all my JS files, so I know it works. Has anyone got it working for loading CSS files as well?
Update: remyabel's solution worked perfectly for loading the physical files, but it seems there are a few quirks to this process...
For some reason, the order in which the CSS files are loaded and whether they're all done in one load(file1,file2); or in stages with load(file1).then(file2); seems to affect how the style rules are applied to the markup. I'm going to set up a few test cases on my local machine to try work out how or why this happens, but for now at least the files are being loaded.
Final Note:
Following on from the solution posted below, I've decided to use head.appendChild(script); instead of head.insertBefore(script, head.firstChild); to add the CSS elements to the DOM (still uses the original method for JS files).
This doesn't affect the order in which files are fetched and processed, but it makes Load.js insert my CSS links in the same order they were listed and at the end of the header instead of the beginning.
Direct from the source code
function asyncLoadScript(src) {
return function (onload, onerror) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
My suggestion is to modify the script (which doesn't seem to contain much) to mirror the function but for a link tag, rather than a script tag.
to reflect OP's comment
The script is built on top of chain.js so it may be more complicated than expected.
Unless you want something else, I'm pretty sure what I wrote above is what you need to change, so it would look like:
function asyncLoadScript(src) {
return function (onload, onerror) {
// Get file extension
var ext = src.split('.').pop();
if (ext == "js")
{
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
} else if (ext == "css")
{
var script = document.createElement('link');
script.type = 'text/css';
script.href = src;
script.rel = "stylesheet";
}
Theoretically that should work. Make another comment if it doesn't work.

Categories