I need to add a Javascript file from the server to the LocalStorage and site header.
i try this code but some things wrong??
var s = document.createElement("script");
s.type = "text/javascript";
s.src = localStorage.theImage;
s.title = "myJavaScript";
$("head").append(s);
function addScript() {
var csvRequest = new Request({
url: "splitNumber.js",
onSuccess: function (response) {
var responseFile = response;
var file = responseFile;
var reader = new FileReader();
reader.onload = function (e) {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = reader.result;
localStorage.theImage = reader.result;
$("head").append(s);
}
reader.readAsDataURL(file);//attempts to read the file in question.
});
}
}
Thanks.
Related
this is my code in componentDidMount(){}
I am trying to initialize the widget popup on page load and then setting the name and email from the received params from the previous page
const fullName = this.state.data[0];
console.log(fullName);
const email = this.state.data[1];
const hashCode = this.state.data[2];
if (window.Tawk_API) {
window.Tawk_API = window.Tawk_API || {};
window.Tawk_LoadStart = new Date();
window.Tawk_API.onLoad = function () {
window.Tawk_API.setAttributes(
{
name: `${fullName}`,
email: `${email}`,
hash: `${hashCode}`,
},
function (error) {}
);
};
}
const tawk = document.getElementById("tawkId");
if (tawk) {
return window.Tawk_API;
}
const script = document.createElement("script");
script.type = "text/javascript";
script.id = "tawkId";
script.async = true;
script.setAttribute("crossorigin", "*");
script.charset = "UTF-8";
script.src = "https://embed.tawk.to/{id}/{id}";
document.head.appendChild(script);
const s0 = document.getElementsByTagName("script")[0];
if (s0 || s0.parentNode) {
s0.parentNode.insertBefore(script, s0);
}
I think you can post by element.
Hi I have a stylesheet and JavaScript function which loads in all the required files for that template.
However I am having a bit of an issue due to when the other script tags run within the template file (plan js code) it does not wait for the required files to load.
So what you have happening is scripts not recognizing functions and other JS functions.
JS Code
<script type="text/javascript">
var uid = '{$smarty.session.ipet_user}';
function stylesheet(url) {
var s = document.createElement('link');
s.rel = 'stylesheet';
s.async = false;
s.href = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
}
function script(url) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
}
(function () {
script('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js');
script('https://apis.google.com/js/api:client.js');
script('https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyBk99v0F4qkmvxifqOD48YktK-QO-3kopI');
script('./templates/main/user-theme/javascript/google.js');
script('plugins/getmdlselect/getmdl-select.min.js');
script('./templates/main/user-theme/javascript/facebook.js');
script('./templates/main/user-theme/javascript/newprofile.js');
script('./templates/main/javascript/zipcode.js');
stylesheet('https://opensource.keycdn.com/fontawesome/4.7.0/font-awesome.min.css');
stylesheet('https://fonts.googleapis.com/css?family=Roboto');
stylesheet('https://fonts.googleapis.com/icon?family=Material+Icons');
stylesheet('./templates/main/user-theme/tpl-files/material.act.css');
stylesheet('plugins/dropzone/dropzone.css');
stylesheet('plugins/stepper/stepper.min.css');
stylesheet('./templates/main/user-theme/tpl-files/style.css');
stylesheet('./templates/main/style/newprofile.css');
stylesheet('plugins/getmdlselect/getmdl-select.min.css');
})();
</script>
You can use load event of <script> and <link> element, Promise constructor and Promise.all() to return a resolved Promise once all requested resources have loaded by passing an array of URL's to request to Array.prototype.map() where each array of URL's is concatenated to a single array where each function is called which returns a Promise
function stylesheet_(url) {
return new Promise(function(resolve, reject) {
var s = document.createElement('link');
s.rel = 'stylesheet';
// s.async = false;
s.href = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
s.onload = resolve;
s.onerror = reject;
})
}
function script(url) {
return new Promise(function(resolve, reject) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = url;
var x = document.getElementsByTagName('head')[0];
x.appendChild(s);
s.onload = resolve;
s.onerror = reject
})
}
function loadStylesAndScripts(styleList = Array(), scriptList = Array()) {
return Promise.all(
styleList.map(stylesheet_)
.concat(scriptList.map(script))
)
}
let requests = loadStylesAndScripts();
requests.then(function() {
console.log("styles and scripts loaded")
})
.catch(function(err) {
console.log("an error occurred requesting styles and scripts")
})
I'm trying to load a js and a css file from within a javascript in chrome I can see that both files are loaded, the mofo alert is triggered, and then the test alert, but not the test2 alert.
Why is that, is there an error in the javascript I can't see?
function loadScript(url, callback){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
document.getElementsByTagName('script')[0].appendChild(script);
}
function loadCss(url, callback){
var elem = document.createElement('link');
elem.href = url;
elem.type = 'text/css';
elem.rel = 'stylesheet';
elem.media = 'all';
document.getElementsByTagName('script')[0].appendChild(elem);
}
var coptaJQStart = function() {
var jQuery_1_11_3 = $.noConflict(true);
alert('test');
};
var coptaCssStart = function() {
alert('test2');
};
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', coptaJQStart);
loadCss('http://www.tffan.com/copta.css', coptaCssStart);
alert('mofo');
You have to attach call back function in loadCss
elem.onreadystatechange = callback;
elem.onload = callback;
function loadScript(url, callback){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
document.getElementsByTagName('script')[0].appendChild(script);
}
function loadCss(url, callback){
var elem = document.createElement('link');
elem.href = url;
elem.type = 'text/css';
elem.rel = 'stylesheet';
elem.onreadystatechange = callback;
elem.onload = callback;
elem.media = 'all';
document.getElementsByTagName('script')[0].appendChild(elem);
}
var coptaJQStart = function() {
var jQuery_1_11_3 = $.noConflict(true);
alert('test');
};
var coptaCssStart = function() {
alert('test2');
};
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', coptaJQStart);
loadCss('http://www.tffan.com/copta.css', coptaCssStart);
alert('mofo');
I want to fetch images from the php web service in my javascript code using json. The alert in the for loop returns "undefined". Please help with your suggestions.
<script>
var menu_category;
var menu_id = [];
var menu_title = [];
var menu_img = [];
"use strict";
function jsonp(url) {
alert("JSONP URL");
var head = document.head;
var script = document.createElement("script");
script.setAttribute("src", url);
head.appendChild(script);
head.removeChild(script);
}
function jsondata(data) {
alert("JSONdata");
var parsedata = JSON.parse(JSON.stringify(data));
var parsed_data = parsedata["main Category"];
for (var i = 1; i <= parsed_data.length; i++) {
alert("FOR");
menu_id[i] = parsed_data.mcatid;
alert(menu_id[i]);
}
}
jsonp("http://remoteaddress/maincategory.php?callback=jsondata");
</script>
I'm writing this code for an extension but It returns:
Origin chrome-extension://gjganecebobheilkbpmhmocibjckgidc is not allowed by Access-Control-Allow-Origin
var randomstring = '';var jsid = 0;
for (var i=0; i<20; i++) {
var rnum = Math.floor(Math.random() * "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".length);
randomstring += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".substring(rnum,rnum+1);
}
function addS(file){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", file, false );
xmlHttp.send( null );
jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
// s.src = file;
s.innerHTML = xmlHttp.responseText;
s.async = "true";
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
addS('https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
addS('http://domain.com/functions.js'');
I would use jQuery but I can't because it breaks the source code of the page, what I want is to do the same as this, but in javascript and skipping that error
function addS(file){
jsid = jsid + 1;
$.get(file, function(data) {
var string = '<script type="text/javascript" async="true" id="'+randomstring+"_unique"+jsid+'" class="'+randomstring+'">'+data+'</script>';
$('head').append(string);
});
Additional Info
I'm gonna insert jquery.js and functions.js with an ID like this tags:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" async="true" id="AWhAXksocT6o6OrBxT28_unique1" class="AWhAXksocT6o6OrBxT28"></script>
<script type="text/javascript" src="http://domain.com/functions.js" async="true" id="AWhAXksocT6o6OrBxT28_unique2" class="AWhAXksocT6o6OrBxT28"></script>
with this code:
function addS(file){
jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = file;
s.async = true;
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
I need this ID (via var randomstring) to keep alive, that's the main problem because I will need to delete both after function ends but it returns
functions.js: Uncaught ReferenceError: randomstring is not defined using this code
$(document).ready(function(){
alert("Functions loaded");
//Do some functions....
$("."+randomstring).delete();
});
Thanks!
You can't perform a cross-domain ajax request unless the domain you are requesting from implements CORS.
What you are doing currently IS a cross-domain ajax request. If you instead do as Sirko suggested and request it by making the src of the script element you are appending the url to the ajax request, it will properly make the request.
function addS(file){
//var xmlHttp = null;
//xmlHttp = new XMLHttpRequest();
//xmlHttp.open( "GET", file, false );
//xmlHttp.send( null );
//jsid = jsid + 1;
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = file;
//s.innerHTML = xmlHttp.responseText;
s.async = "true";
s.id = randomstring+"_unique"+jsid;
s.className = randomstring;
document.head.appendChild(s);
}
What is the purpose of this function? In what context is it used? What does it accomplish?
As far as I can see, you're just pasting the content of a file into the script tag.
So why not pass the file url directly to the src parameter of the script tag instead?
function addS( file ) {
var scriptEl = document.createElement( 'script' );
scriptEl.setAttribute( 'src', file ) ;
document.head.appenChild( scriptEl );
}