How to add a lazy load to the script? - javascript

There is a script:
<script>
$(function (){
$('#jstree')
.jstree({
"plugins": [ "dnd", "sort", "json_data" ],
'core':{
"check_callback" : true,
"plugins" : ["contextmenu", "dnd"],
'data': {
'url': function (node) {
return node.id === '#' ? 'ajax?id=root' : 'ajax?id=' + node.id;
},
'data': function (node) {
return { 'id': node.id };
}
}
}
});
});
</script>
I need to add a delay (2 sec) on opening nodes. I readed jQuery documentation but i didn't find an answer there. Please help me how add a delay?

Answer referenced from combined two other SO answers.
Essentially, set a timeout function when the DOM loads and create a <script> tag at run time. Then just append it to the <body> and it will load.
console.log("Seconds: " + new Date().getSeconds());
setTimeout(function() {
var blob = new Blob(["console.log('Loaded after')"]); // Insert JS code into []
var script = document.createElement('script');
var url = URL.createObjectURL(blob);
script.onload = script.onerror = function() {
URL.revokeObjectURL(url);
};
script.src = url;
document.body.appendChild(script);
console.log("Seconds: " + new Date().getSeconds());
}, 2000);
<html>
<head>
</head>
<body>
<p>foo</p>
</body>
</html>

Related

I want to run a script using javascript how do I do it?

When I click a button I want a script that I have on my computer to run. It can be a simple print "Hello World".
How do I do that ? What I have is this :
I don't have the litle idea how do this could be done please can you help?
HTML
<input class="buttonRun" type="button" value="Run" id="btnRun"/>
function runScript() {
}
$("#btnRun").click(function () {
runScript();
});
Python
print ("Hello World");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="buttonRun" type="button" value="Run" id="btnRun"/>
<script>
function runScript() {
alert('Hello World!');
}
$("#btnRun").click(function () {
runScript();
});
</script>
Here you can pass the scriptUrl to this function and it will load all the methods and variable that has been wriiten in the script file.
loadExternalScript(scriptUrl: string) {
return new Promise((resolve, reject) => {
const scriptElement = document.createElement('script')
scriptElement.src = scriptUrl
scriptElement.onload = resolve
document.body.appendChild(scriptElement)
});
}
may this help for you:
You may dynamically need to append the script in your tag like this
try this
function runScript(){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange = function () {
if (this.readyState === 'complete' || this.readyState === 'loaded') {
callback();
}
};
script.onload = callback;
script.src = 'Your scripts path ';
head.appendChild(script);
}

Load Javascript file with Javascript based on URL

Can I use Javascript to load a Javascript file in HTML based on a string in URL?
For example something like this:
<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1)
{
include ('javascript_deutch.js)
}
else
{
include ('javascript_english.js)
}
</script>
I cannot use any other method like PHP or something.
Thanks for the help guys.
Unfortunately none of these things seem to work.
This
<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1) {
document.head.innerHTML+='<script src="javascript_deutch.js"></script>';
}else{
document.head.innerHTML+='<script src="javascript_english.js"></script>';
}
</script>
ended up just displaying a message at the top of my page:
'; }else{ document.head.innerHTML+=''; }
And this
<script type="text/javascript">
var script = document.createElement('script');
if (location.path.indexOf("DEUTCH") > -1) {
script.src = 'javascript_deutch.js';
} else {
script.src = 'javascript_english.js';
}
document.body.appendChild(script);
</script>
did not request the files on the server at all.
Am I missing something?
You can create a <script> tag dynamically:
var script = document.createElement('script');
if (location.path.indexOf("DEUTCH") > -1) {
script.src = 'javascript_deutch.js';
} else {
script.src = 'javascript_english.js';
}
document.body.appendChild(script);
The easy way without framework:
var _script = document.createElement('script');
_script.src = 'fileName.js';
document.body.appendChild(_script);
May be will be good to isolate this into separate function like this:
function includeJsFile(fileName) {
var _script = document.createElement('script');
_script.src = fileName;
document.body.appendChild(_script);
}
But may be will be good for you to check
http://requirejs.org/
Why not. Just add them in the script tags.
<script type="text/javascript">
if (location.href.indexOf("DEUTCH") != -1) {
document.head.innerHTML+='<script src="javascript_deutch.js"></script>';
}else{
document.head.innerHTML+='<<script src="javascript_english.js"></script>';
}
</script>
Try this code, this method worked for me:
<script>
document.write('<script type="text/javascript" src="' + language-file + '.js"><\/script>')
</script>

how to use Postmedia digital cordova plugin (DFP)

I would like to use DFP (double click for Plublisher) for my android app, I already have the generated scripts and markup as below:
<script type='text/javascript'>
(function() {
var useSSL = 'https:' == document.location.protocol;
var src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
document.write('<scr' + 'ipt src="' + src + '"></scr' + 'ipt>');
})();
</script>
<script type='text/javascript'>
googletag.defineSlot('/*****/****_APP_1024x66', [1024, 66], 'div-gpt-ad- ********-0').addService(googletag.pubads());
googletag.pubads().enableSyncRendering();
googletag.pubads().enableSingleRequest();
googletag.enableServices();
</script>
DOCUMENT BODY
<div id='div-gpt-ad-**********' style='width:1024px; height:66px;'>
<script type='text/javascript'>
googletag.display('div-gpt-ad-*********');
</script>
</div>)
But, it does not display on Mobile (android project). That's why I would like to use the DFP plugin (PostMedia), but I do not know how to use that? as the plugin itself would not be good enough.
for instance, I have already had the code(above) to put in my app, but I wanna know how can i integrate that plugin with my code.
Note: In the plugin we have:
createBannerAd: function (options, successCallback, failureCallback) {
var defaults = {
'adUnitId': 1404187116182-0,
'adSize': (250, 150),
'tags': undefined,
'networkId': 4271715,
'backgroundColor': "#fff"
};
what if we want to have bunch of ads and of course we have bunch of codes generated by Google and FDP? we need to create a service ? or what?
I really appreciate any response a head,
I am using Cordova 2.8.1 / AngularJS
Here is how we use it
var successCreateBannerView = function() {
//console.log("addBanner Success");
DFPPlugin.requestAd({
'isTesting': false
}, success, error);
};
var success = function() {
//console.log("requestAd Success");
};
var error = function(message) {
//console.log("requestAd Failed " + message);
};
var options = {
'adUnitId': '/xxx/xxxx', // Replace the /xxx/xxxx with your adslot
'adSize': 'BANNER',
'tags': {},
'backgroundColor': '#FFFFFF'
};
DFPPlugin.createBannerAd(options, successCreateBannerView, error);

Get the status of an object on eventhandling in JavaScript

My source code :
<!doctype html>
<html>
<head>
<title>onload test</title>
<link type="text/css" rel="stylesheet" href="spot.css" media="screen" />
</head>
<body>
<h1>Welcome Page</h1>
<script>
debugger;
function constructScripts(url, callBack) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
if (script.readyState) {
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null; callBack();
}
};
}
else {
script.onload = callBack;
}
}
</script>
<script>
debugger;
myCallBack = function () {
alert(this.src + "loaded");
}
constructScripts("files1", myCallBack);
constructScripts("files2", myCallBack);
constructScripts("files3", myCallBack);
</script>
</body>
</html>
this.src is undefined here. I guess this should be an 'script' object which supposed to have its src property so that I can read the filename. Who is this here? And also when I view the page source these scripts were not included in the header() section. Why is it so?
this.src is undefined here.
It shouldn't be… It is defined earlier: script.src = url
I guess this should be an 'script' object which supposed to have its src property so that i can read the filename. Who is 'this' here?
The script element upon which the onload or readystatechange event fires
And also when i view the page source these scripts were not included in the header() section. Why is it so?
Because you are looking at the page source, not a serialisation of the live DOM after it has been manipulated by JavaScript.
When you call you callBack function, pass it the script object like callBack(script). Modify the callBack function like
myCallBack = function (script) {
alert(script.src + "loaded");
}
View source does not show dinamically loaded elements.
You need to extend your function using prototype.
Element.prototype.MyMethod = function(){}
Look at your edited code
<!doctype html>
<html>
<head>
<title>onload test</title>
<link type="text/css" rel="stylesheet" href="spot.css" media="screen" />
</head>
<body>
<h1>Welcome Page</h1>
<script>
Element.prototype.MyMethod = function(){}
function constructScripts(url, callBack) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
script.MyMethod = callBack;
document.getElementsByTagName("head")[0].appendChild(script);
if (script.readyState) {
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
script.MyMethod();
}
};
}
else {
script.onload = callBack;
}
}
</script>
<script>
myCallBack = function () {
alert(this.src + "loaded");
}
constructScripts("files1", myCallBack);
constructScripts("files2", myCallBack);
constructScripts("files3", myCallBack);
</script>
</body>
</html>

Javascript access denied error on page partial load - why?

On thirdpartydomain.com I want to embed a simple <script> tag that pulls in a script from mydomain.com/myscript.js, which simply creates a little <div> and pulls partial page content from mydomain.com/mypage.htm.
Here's the script, adapted from: How to embed Javascript widget that depends on jQuery into an unknown environment
var myEmbedId = '12345';
var myEmbedContainerId = 'myEmbedContainer_' + myEmbedId;
document.write('<div id="' + myEmbedContainerId + '">IF ALL GOES WELL, THIS TEXT WILL BE REPLACED WITH MYPAGE.HTM CONTENTS');
document.write('</div>');
(function (window, document, version, callback) {
var j, d;
var loaded = false;
if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://mydomain.com/jquery-1.4.1.min.js";
script.onload = script.onreadystatechange = function () {
if (!loaded && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
callback((j = window.jQuery).noConflict(1), loaded = true);
j(script).remove();
}
};
document.documentElement.childNodes[0].appendChild(script)
}
})(window, document, "1.3", function ($, jquery_loaded) {
$(document).ready(function () {
alert('jquery loaded!');
var myRefreshUrl = 'http://mydomain.com/mypage.htm';
alert('refreshing from ' + myRefreshUrl);
$.get(myRefreshUrl, function(data){
var returnData = data;
alert('return data: ' + data);
$('#' + myEmbedContainerId).html(data); });
alert('load complete v2');
});
});
In IE, I get an Access Denied error from Javascript; in Firefox I just get no data returned.
What's wrong with this?
You cannot create an AJAX request to a different domain from the one that is hosting the current window context.
To pull off what you're describing, you can do something like:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://mydomain.com/dynamic.js?data=somepage.htm';
someContainer.appendChild(script);
Within that dynamic.js, you can wrap the HTML contents in a document.write(). The net effect is the same as inserting the result of the AJAX request at the same point in the DOM.

Categories