JavaScript src onload - javascript

Ok, I have this code:
<script language="javascript">
window.onload = function(){
var s = document.createElement('script');
s.src = 'jscript.js';
document.getElementsByTagName('body')[0].appendChild(s);
} </script>
<script type="text/javascript" src="https://www.facebook.com/dragosgaftoneanu"
onload = "alert('logged in')"
onerror="alert('not logged in)">
</script>
I want to execute the code from the first script at the onload of the second script. I have jscript.js where it is defined function().

as what i understand, do you want to call the first js file using the second js file?
here is the code
in your file2.html you need to add the src of the first file
<script language="javascript" src='location'></script>
<script language="javascript">
function init()
{
name();//call the function name. It's either in this file or in your first file
}
</script>
<body onload="init()">

Related

Preload polyfills before executing main code

I'm trying to load some polyfills only if the user needs them but I can't get the scripts to download and be executed in order causing errors.
Dependencies have the asynchronous attribute and the main code has the defer attribute although is located at the end of the body tag so much of the parsing is already done.
Is there any simple way of doing this without using a preloader?
<html>
<head>
</head>
<body>
<script>
// Google Analytics
</script>
<script>
var firstScript = document.getElementsByTagName('script')[0];
if (!self.fetch) {
var fetchScript = document.createElement('script');
fetchScript.src = '/js/fetch.min.js';
fetchScript.async = 1;
firstScript.parentNode.insertBefore(fetchScript , firstScript);
}
if (!self.URLSearchParams) {
var urlspScript = document.createElement('script');
urlspScript.src = '/js/url-search-params.min.js';
urlspScript.async = 1;
firstScript.parentNode.insertBefore(urlspScript , firstScript);
}
</script>
<script defer src="/js/main.min.js"></script>
</body>
</html>

html5 template content (document fragment) load order on appendChild

consider the following code -->
<template id="foo">
<script type="text/javascript">
console.log("00000000");
</script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
console.log(11111111);
</script>
<script type="text/javascript">
console.log(22222222);
var xyz = $;
console.log(33333333);
</script>
</template>
now on appending this to the DOM
var template = document.getElementById('foo')
var clone = document.importNode(template.content,true);
document.appendChild(clone);
gives this output in console -->
00000000
11111111
22222222
Uncaught ReferenceError: $ is not defined
So the question in general is -->
How to properly load into DOM, an html <template> that has
an external script (like jQuery in this case), followed by an inline script having some dependency on it.
Also - this does not happen if template tag is removed -->
<script type="text/javascript">
console.log("00000000");
</script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
console.log(11111111);
</script>
<script type="text/javascript">
console.log(22222222);
var xyz = $;
console.log(33333333);
</script>
How in the latter case, does the browser download it synchronously?
Is it possible to have blocking script download (line by line) in the former case (with template) ?
The problem is that the script is loaded async. That means that it start to load the script from the web, but continues running the code below. So in that case it will execute code below without having loaded jQuery yet.
You only need to load it once, so you could do it at the start, and only once:
var template = document.getElementById('foo')
var clone = document.importNode(template.content,true);
document.body.appendChild(clone);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<template id="foo">
<script type="text/javascript">
console.log(00000000);
</script>
<script type="text/javascript">
console.log(11111111);
</script>
<script type="text/javascript">
console.log(22222222);
var xyz = $;
console.log(33333333);
</script>
</template>
Another option would be to make sure code below is only executed once the file is loaded:
var template = document.getElementById('foo')
var clone = document.importNode(template.content, true);
document.body.appendChild(clone);
<template id="foo">
<script type="text/javascript">
console.log(00000000);
</script>
<script type="text/javascript">
function scriptOnload() {
console.log(11111111);
console.log(22222222);
var xyz = $;
console.log(33333333);
}
</script>
<script onload="scriptOnload()" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</template>
Here's how I handle it in my application (with jQuery):
//Load the template from an external file and append it to the HEAD of the document
$.get("/path/to/your_external_template_file.html", function (html_string) {
$('head', top.document).append(
new DOMParser().parseFromString(html_string, 'text/html').querySelector('template')
);
}, 'html');
//Locate the template after you've imported it
var $template = $("#top_template_element_id");
//If you want to reuse the content, be sure to clone the node.
var content = $template.prop('content').cloneNode(true);
//Add a copy of the template to desired container on the page
var $container = $('#target_container_id').append(content);

jquery to run in iframe when created on the fly

I am trying to first create an iframe and then inject into it jQuery library and then have an alert to say that jQuery has loaded.
The jQuery library is being inserted into the iframe head as expected and the alert on jQuery load into the body.
The problem is, it does not show the alert and instead says jQuery is not defined.
Can anyone suggest anything?
Here is the code
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<title>iFrame Test</title>
</head>
<body>
<script>
var insertScript = function(src){
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = false;
script.src = src;
$('iframe').contents().find('head')[0].appendChild(script);
}
var insertScriptContent = function(code){
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = false;
script.innerHTML = code;
$('iframe').contents().find('body')[0].appendChild(script);
}
$(function(){
$('iframe').load(function(){
var contents = $('iframe').contents();
insertScript('https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js');
insertScriptContent('jQuery(function(){ alert("loaded"); });');
});
});
</script>
<div class="output">
<iframe></iframe>
</div>
</body>
</html>
You're loading jQuery asynchronously (despite the script.async=false) and then loading your alert script immediately after that. jQuery is not yet loaded when that script runs, so you get the undefined jQuery reference.
As a quick fix, I added a setInterval() that waits until jQuery is defined. I also made these other changes:
Removed the script.async = false; both places because it doesn't do any good.
Removed the $('iframe').load() wrapper. When I tested your code, the callback function in that wrapper never gets called at all. That's not surprising since nothing is being loaded into the iframe at that point.
Changed the two places where you use document.createElement() to use the iframe document (called iframedoc in my version) instead. It works OK using document, but I'm a bit more comfortable creating those scripts under the document they will be loaded into.
Changed two instances of ...find(something)[0].appendChild(); to the simpler ...find(something).append();.
Here's the working code:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript">
</script>
<title>iFrame Test</title>
</head>
<body>
<script type="text/javascript">
$(function() {
var $contents = $('iframe').contents();
var iframedoc = $contents[0];
var insertScript = function(src) {
var script = iframedoc.createElement('script');
script.type = 'text/javascript';
script.src = src;
$('iframe').contents().find('head').append(script);
}
var insertScriptContent = function(code) {
var script = iframedoc.createElement('script');
script.type = 'text/javascript';
script.innerHTML = code;
$('iframe').contents().find('body').append(script);
}
insertScript('https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js');
insertScriptContent(
'var timer = setInterval( function() {' +
'if( typeof jQuery == "undefined" ) return;' +
'clearInterval( timer );' +
'jQuery(function(){ alert("loaded"); });' +
'}, 50 )'
);
});
</script>
<div class="output">
<iframe></iframe>
</div>
</body>
</html>
That was good for a first pass, but there's a simpler way to do it. I tried replacing the two script functions with jQuery code, so here is another working version:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript">
</script>
<title>iFrame Test</title>
</head>
<body>
<script type="text/javascript">
$(function() {
var $contents = $('iframe').contents();
$contents.find('head').append(
'<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"><\/script>'
);
$contents.find('body').append(
'<script>' +
'jQuery(function(){ alert("loaded"); });' +
'<\/script>'
);
});
</script>
<div class="output">
<iframe></iframe>
</div>
</body>
</html>
Oddly enough, this one works OK without the setInterval() timer, so I took that code out. I'm not sure exactly why this works - which is not a comforting feeling - but it does seem to be consistent in the browsers I tested it in.
And finally, here is a non-working experiment. In the past I've used document.write() targeting an iframe to good effect. So I thought I would try that:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript">
</script>
<title>iFrame Test</title>
</head>
<body>
<script type="text/javascript">
$(function() {
var $contents = $('iframe').contents();
var iframedoc = $contents[0];
iframedoc.write(
'<!doctype html>',
'<html>',
'<head>',
'<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"><\/script>',
'</head>',
'<body>',
'<script>',
'debugger;',
'jQuery( function(){ alert("loaded"); } );',
'<\/script>',
'</body>',
'</html>'
);
});
</script>
<div class="output">
<iframe></iframe>
</div>
</body>
</html>
This version does load jQuery and the inline script into the iframe, and it executes the jQuery() call in the inline script. But it never calls the callback function with the alert() in it. This actually relates to something I'm working on, so I'll probably take another look at it tomorrow, but in the meantime I left the experimental code in case you're curious. I changed it to use the uncompressed jQuery inside the iframe for easy debugging, and left a debugger; statement in there.

what if jquery.js is include into the page twice?

If I introduce the jquery.js into the page twice(unintentional OR intentional), what will happen?
Is there any mechanism in jquery that can handle this situation?
AFAIK, the later one jquery will overwrite the previous one, and if there is some action binding with the previous one, it will be cleared.
What can I do to avoid the later one overwrite the previous one?
===edited===
I couldn't understand WHY this question got a down vote. Could the people who give the down vote give out the answer?
==edited again==
#user568458
u r right, now it's the test code:
<html>
<head>
</head>
<body>
fast<em id="fast"></em><br>
slow<em id="slow"></em><br>
<em id="locker"></em>
</body>
<script type="text/javascript">
function callback(type){
document.getElementById(type).innerHTML=" loaded!";
console.log($.foo);
console.log($);
console.log($.foo);
$("#locker").html(type);
console.log($("#locker").click);
$("#locker").click(function(){console.log(type);});
$.foo = "fast";
console.log($.foo);
}
function ajax(url, type){
var JSONP = document.createElement('script');
JSONP.type = "text/javascript";
JSONP.src = url+"?callback=callback"+type;
JSONP.async = JSONP.async;
JSONP.onload=function(){
callback(type);
}
document.getElementsByTagName('head')[0].appendChild(JSONP);
}
</script>
<script>
ajax("http://foo.com/jquery.fast.js", "fast");
ajax("http://foo.com/jquery.slow.js", "slow");
</script>
</html>
it produced the result:
undefined test:12
function (a,b){return new e.fn.init(a,b,h)} test:13
undefined test:14
function (a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)} test:16
fast test:19
undefined test:12
function (a,b){return new e.fn.init(a,b,h)} test:13
undefined test:14
function (a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)} test:16
fast
the token "$" of the previous one(jquery.fast.js) is overwrite by the later(jquery.slow.js) one.
Is there any method to avoid the overwriting?
I did try this code:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$('#try').click(function() {
alert('ok');
});
});
</script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<button id="try">Try me</button>
</body>
</html>
Nothing happend. On click I've got an alert. Same result if the second jquery.js loaded in body tag before or after the button.

Image roll over script not working as expected

This is how I am calling the JavaScript function in my HTML page:-
<script type="text/javascript" src="imagerollover.js"></script>
</script>
<script type="text/javascript">
//Following function should be called at the end of the page:
imagerollover();
</script>
</head>
<body>
.
.
.
this is my imagerollover.js:-
function imagerollover(){
var allimages=document.getElementsByTagName("img")
var preloadimages=[]
for (var i=0; i<allimages.length; i++){
if (allimages[i].getAttribute("data-over")){ //if image carries "data-over" attribute
preloadimages.push(new Image()) //preload "over" image
preloadimages[preloadimages.length-1].src=allimages[i].getAttribute("data-over")
allimages[i].onmouseover=function(){
this.src=this.getAttribute("data-over")
}
allimages[i].onmouseout=function(){
this.src=this.getAttribute("data-out")
}
} //end if
} //end for loop
}
//Usage: Call following function at the end of the page:
//imagerollover()
Image tags:
<img src="knitting1.jpg"
data-over="knitting2.jpg"
data-out="knitting1.jpg"
alt="Logo" width="400px" height="90" align="middle" />
Also, both images knitting1.jpg and knitting2.jpg exist in my site's root folder. I don't know what is wrong.
I placed an alert inside imagerollover.js file in the beginning. It is getting called but it is not showing any roll over effect. Why?
You need to run this onload - your images tags are not yet available to the script when you execute the function - you are not actually following the instruction of the script which should have been placed at the end of the page or in my suggestion in the onload
<head>
<script type="text/javascript" src="imagerollover.js"></script>
</script>
<script type="text/javascript">
window.onload=function()
//Following function should be called at the end of the page OR on window.onload!
imagerollover();
}
</script>
</head>

Categories

Resources