Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

javascript - How to add DOM element script to head section?

I want to add DOM element to head section of HTML. jQuery does not allow adding DOM element script to the head section and they execute instead, Reference.

I want to add script tags and write a script within <head> section.

var script = '<script type="text/javascript"> //function </script>'
$('head').append(script);

Something like this with functions. I tried jQuery and javascript, but it does not work.

Please tell me how to add and write script to head by jQuery or javascript.

I tired the javascript to add DOM element, but it does not work with .innerHTML() to write to head. I am using jQuery 2.0.3 and jQuery UI 1.10.3.

I want to add base64 encoded script to head section. I use base64 decoder js like this to decode the javascript and then put on the head section.

//Edited
It will be

$.getScript('base64.js');
var encoded = "YWxlcnQoImhpIik7DQo="; //More text
var decoded = decodeString(encoded);
var script = '<script type="text/javascript">' +decoded + '</script>';
$('head').append(script);

To fit an encoded script and the addition in one javascript file. I want to use base64.js or some other decoder javascript files for browsers does not accept atob().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try this

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'url';    

document.head.appendChild(script);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...